下面列出了org.springframework.security.core.GrantedAuthority#getAuthority ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException {
JwtUser jwtUser = (JwtUser) authResult.getPrincipal();
boolean isRemember = rememberMe.get() == 1;
String role = "";
Collection<? extends GrantedAuthority> authorities = jwtUser.getAuthorities();
for (GrantedAuthority authority : authorities){
role = authority.getAuthority();
}
String token = JwtTokenUtils.createToken(jwtUser.getId(),jwtUser.getUsername(), role, isRemember);
response.setHeader("token", JwtTokenUtils.TOKEN_PREFIX + token);
response.setCharacterEncoding("UTF-8");
Map<String, Object> maps = new HashMap<>();
maps.put("data", JwtTokenUtils.TOKEN_PREFIX + token);
maps.put("roles", role.split(SPLIT_COMMA));
response.getWriter().write(JSON.toJSONString(new ReturnT<>(maps)));
}
/**
* This method extracts the roles of currently logged-in user and returns
* appropriate URL according to his/her role.
*/
protected String getUrl(Authentication authentication) {
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
String role = grantedAuthority.getAuthority();
if (role.equalsIgnoreCase(("ROLE_ADMIN"))) {
return "/admin";
} else if (role.equalsIgnoreCase(("ROLE_USER"))) {
return "/home";
} else if (role.equalsIgnoreCase(("ROLE_DBA"))) {
return "/dba";
} else {
// throw new IllegalStateException();
}
}
return "/";
}
/**
* Authorities could be ADMIN, ROLE, SCOPE:ROLE
* Priority is:
* 1 - ADMIN
* 2 - SCOPE:ROLE
* 3 - ROLE
* @param roleScope the scope we're looking for
* @param authorities the authorities to parse
* @return the role
*/
private String getRoleFromAuthorities(RoleScope roleScope, Collection<? extends GrantedAuthority> authorities) {
String globalRole = null;
String specificRole = null;
for (GrantedAuthority grantedAuthority : authorities) {
String authority = grantedAuthority.getAuthority();
if (SystemRole.ADMIN.name().equals(authority)) {
return authority;
}
if (authority.contains(":")) {
String[] scopeAndName = authority.split(":");
if (roleScope.name().equals(scopeAndName[0])) {
specificRole = scopeAndName[1];
}
} else {
globalRole = authority;
}
}
return specificRole != null ? specificRole : globalRole;
}
public static Set<String> getUserRoles(Object securityContext) {
Set<String> roleSet = new TreeSet<String>();
if (securityContext != null) {
SecurityContext sc = (SecurityContext) securityContext;
if (sc.getAuthentication() != null) {
Collection<? extends GrantedAuthority> authorities = sc.getAuthentication().getAuthorities();
if (authorities != null) {
for (GrantedAuthority authority : authorities) {
String auth = authority.getAuthority();
if (auth.startsWith("ROLE_")) {
auth = auth.substring(5);
}
roleSet.add(auth);
}
}
}
}
return Collections.unmodifiableSet(roleSet);
}
@Test
public void testUserDaowithValidUserLoginAndPassword() {
Properties userLogins = new Properties();
userLogins.put("admin", "ADMIN::admin123");
UserDao user = new UserDao();
user.setUserLogins(userLogins);
User userBean = user.loadUserByUsername("admin");
assertTrue(userBean.getPassword().equals("admin123"));
Collection<? extends GrantedAuthority> authorities = userBean.getAuthorities();
String role = "";
for (GrantedAuthority gauth : authorities) {
role = gauth.getAuthority();
}
assertTrue("ADMIN".equals(role));
}
public static boolean isAdmin() {
SecurityContext context = SecurityContextHolder.getContext();
if (context != null) {
Authentication authentication = context.getAuthentication();
if (authentication != null) {
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
if (authorities != null) {
for (GrantedAuthority authority : authorities) {
if (authority != null) {
String authorityString = authority.getAuthority();
if (Constants.ROLE_IT_ADMINISTRATOR.equals(authorityString)) {
return true;
}
}
}
}
}
}
return false;
}
@Test
public void testUserDaowithValidUserLoginAndPassword() {
Properties userLogins = new Properties();
userLogins.put("admin", "ADMIN::admin123");
UserDao user = new UserDao();
user.setUserLogins(userLogins);
User userBean = user.loadUserByUsername("admin");
assertTrue(userBean.getPassword().equals("admin123"));
Collection<? extends GrantedAuthority> authorities = userBean.getAuthorities();
String role = "";
for (GrantedAuthority gauth : authorities) {
role = gauth.getAuthority();
}
assertTrue("ADMIN".equals(role));
}
/**
* 判定是否拥有权限的决策方法
* @param authentication CustomUserDetailsService类loadUserByUsername()方法中返回值
* @param o 包含客户端发起的请求的request信息。
* @param collection CustomFilterInvocationSecurityMetadataSource类的getAttribute()方法返回值
* @throws AccessDeniedException
* @throws InsufficientAuthenticationException
*/
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
String url;
for (GrantedAuthority ga : authentication.getAuthorities()) {
url = ga.getAuthority();
if(url.equals(request.getRequestURI())){
return;
}
}
throw new AccessDeniedException("没有权限访问");
}
/**
* 判定是否拥有权限的决策方法
* @param authentication CustomUserDetailsService类loadUserByUsername()方法中返回值
* @param o 包含客户端发起的请求的request信息。
* @param collection CustomFilterInvocationSecurityMetadataSource类的getAttribute()方法返回值
* @throws AccessDeniedException
* @throws InsufficientAuthenticationException
*/
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
String url;
for (GrantedAuthority ga : authentication.getAuthorities()) {
url = ga.getAuthority();
if(url.equals(request.getRequestURI())){
return;
}
}
throw new AccessDeniedException("没有权限访问");
}
/**
* 判定是否拥有权限的决策方法
* @param authentication CustomUserDetailsService类loadUserByUsername()方法中返回值
* @param o 包含客户端发起的请求的request信息。
* @param collection CustomFilterInvocationSecurityMetadataSource类的getAttribute()方法返回值
* @throws AccessDeniedException
* @throws InsufficientAuthenticationException
*/
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
String url;
for (GrantedAuthority ga : authentication.getAuthorities()) {
url = ga.getAuthority();
if(url.equals(request.getRequestURI())){
return;
}
}
throw new AccessDeniedException("没有权限访问");
}
@Override
public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) {
// 获得loadUserByUsername()方法的结果
User user = (User)authentication.getPrincipal();
// 获得loadUserByUsername()中注入的角色
Collection<GrantedAuthority> authorities = user.getAuthorities();
// 遍历用户所有角色
for(GrantedAuthority authority : authorities) {
String roleName = authority.getAuthority();
Integer roleId = roleService.getByName(roleName).getId();
// 得到角色所有的权限
List<SysPermission> permissionList = permissionService.listByRoleId(roleId);
// 遍历permissionList
for(SysPermission sysPermission : permissionList) {
// 获取权限集
List permissions = sysPermission.getPermissions();
// 如果访问的Url和权限用户符合的话,返回true
if(targetUrl.equals(sysPermission.getUrl())
&& permissions.contains(targetPermission)) {
return true;
}
}
}
return false;
}
/**
*
*/
@Override
public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) {
// 获得loadUserByUsername()方法的结果
User user = (User) authentication.getPrincipal();
// 获得loadUserByUsername()中注入的角色
Collection<GrantedAuthority> authorities = user.getAuthorities();
// 遍历用户所有角色
for (GrantedAuthority authority : authorities) {
String roleName = authority.getAuthority();
Integer roleId = roleService.selectByName(roleName).getId();
// 得到角色所有的权限
List<SysPermission> permissionList = permissionService.listByRoleId(roleId);
// 遍历权限
for (SysPermission sysPermission : permissionList) {
// 获取权限集
List permissions = sysPermission.getPermissions();
// 如果访问的Url和权限用户符合的话,返回true
if (targetUrl.equals(sysPermission.getUrl())
&& permissions.contains(targetPermission)) {
return true;
}
}
}
return false;
}
@Override
protected String determineTargetUrl(final HttpServletRequest request, final HttpServletResponse response) {
final Authentication authentication = authenticationInformationRetriever.getAuthentication();
for (final GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
final String authority = grantedAuthority.getAuthority();
if (roleDefault.equalsIgnoreCase(authority)) {
return configUrl;
}
}
return applicationUrl;
}
public int compare(GrantedAuthority g1, GrantedAuthority g2) {
if (g2.getAuthority() == null) {
return -1;
}
if (g1.getAuthority() == null) {
return 1;
}
return g1.getAuthority().compareTo(g2.getAuthority());
}
public static Set<String> getCurrentAuthorityUrl() {
Set<String> path = Sets.newHashSet();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (final GrantedAuthority authority : authorities) {
String url = authority.getAuthority();
if (StringUtils.isNotEmpty(url)) {
path.add(url);
}
}
path.add(AUTH_LOGIN_AFTER_URL);
path.add(AUTH_LOGOUT_URL);
return path;
}
public int compare(GrantedAuthority g1, GrantedAuthority g2) {
// Neither should ever be null as each entry is checked before adding it to the set.
// If the authority is null, it is a custom authority and should precede others.
if (g2.getAuthority() == null) {
return -1;
}
if (g1.getAuthority() == null) {
return 1;
}
return g1.getAuthority().compareTo(g2.getAuthority());
}
private Subject buildSubject(final Authentication authentication) {
Subject s = new Subject();
s.getPrincipals().add(new SimplePrincipal(authentication == null ? ANONYMOUS:authentication.getName()));
if (authentication != null) {
SimpleGroup g = new SimpleGroup("Roles");
for (GrantedAuthority ga : authentication.getAuthorities()) {
String role = ga.getAuthority();
g.addMember(new SimplePrincipal(role));
}
s.getPrincipals().add(g);
}
return s;
}
public static String buildRoleCode(GrantedAuthority role) {
String result = role.getAuthority();
if (role instanceof SysRole) {
result = RoleType.SYS_ROLE.name() + ":" + result;
}
else {
result = RoleType.APP_ROLE.name() + ":" + result;
}
return result;
}
public AuthorityImpl(GrantedAuthority grantedAuthority) {
this(grantedAuthority.getAuthority());
}
/**
* create instance with data from specified authority
* @param authority
* @return
*/
public static GrantedAuthorityImpl from(GrantedAuthority authority) {
return new GrantedAuthorityImpl(authority.getAuthority(), MultiTenancySupport.getTenant(authority));
}