本文整理汇总了Java中org.springframework.security.core.authority.SimpleGrantedAuthority类的典型用法代码示例。如果您正苦于以下问题:Java SimpleGrantedAuthority类的具体用法?Java SimpleGrantedAuthority怎么用?Java SimpleGrantedAuthority使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SimpleGrantedAuthority类属于org.springframework.security.core.authority包,在下文中一共展示了SimpleGrantedAuthority类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: loadUserByUsername
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
/**
* Get user by username. Login process.
*
* @param username The user's name
* @return UserDetails object
* @throws UsernameNotFoundException No user found
*/
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
log.info("Called with username {}", username);
Optional<UserEntity> userOptional = userRepository.findByUsernameIgnoreCaseAndEnabledTrue(username);
userOptional.orElseThrow(() -> new UsernameNotFoundException("No user found with username " + username));
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for(SecurityRole role : userOptional.get().getAuthorities()) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.toString()));
}
return new org.springframework.security.core.userdetails.User(userOptional.get().getUsername(),
userOptional.get().getPassword(),
grantedAuthorities);
}
示例2: testJWTFilter
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Test
public void testJWTFilter() throws Exception {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"test-user",
"test-password",
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
);
String jwt = tokenProvider.createToken(authentication, false);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
示例3: loadUserByUsername
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
CalendarUser user = userRepository.findByEmail(username);
if (user == null)
throw new UsernameNotFoundException("username " + username
+ " not found");
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()){
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities);
}
示例4: alimenteSecurityUserCptMin
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
/**
* Alimente la session pour un compte local
*
* @param cptMin
* le compte a minima a connecter
*/
public void alimenteSecurityUserCptMin(CompteMinima cptMin) {
SecurityUser user = (SecurityUser) getCurrentUser();
if (user != null) {
List<GrantedAuthority> authoritiesListe = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority sga = new SimpleGrantedAuthority(ConstanteUtils.ROLE_CANDIDAT);
authoritiesListe.add(sga);
SecurityUserCandidat securityUserCandidat = new SecurityUserCandidat(user.getUsername(),
user.getDisplayName(), authoritiesListe, cptMin.getIdCptMin(), cptMin.getNumDossierOpiCptMin(),
cptMin.getTemValidCptMin(), cptMin.getTemValidMailCptMin(), null);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
securityUserCandidat, securityUserCandidat.getUsername(), securityUserCandidat.getAuthorities());
Authentication authentication = authenticationManagerCandidat.authenticate(authRequest);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
UI.getCurrent().getSession().getSession()
.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
}
}
示例5: getGrantedAuthorities
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
private List<GrantedAuthority> getGrantedAuthorities(User user) {
/*
For now users can only have 1 role at a time. You cannot have more than 1 role type.
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
UserDetail userDetail = user.getUserDetail();
String[] list = (userDetail.getType()).split(",");
for(String i : list){
authorities.add(new SimpleGrantedAuthority("ROLE_"+i));
}
return authorities;
*/
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getUserDetail().getType()));
return authorities;
}
示例6: parseUserFromToken
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
public User parseUserFromToken(String token) {
try {
String username = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
String roleString = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token).getBody().get("roles", String.class);
List<SimpleGrantedAuthority> roles = new ArrayList<>();
if (!StringUtils.isEmpty(roleString)) {
String[] roleValues = StringUtils.split(roleString, ",");
for (String roleValue : roleValues) {
roles.add(new SimpleGrantedAuthority(roleValue));
}
}
return new User(username, token, roles);
} catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
throw new BadCredentialsException("Invalid JWT token: ", ex);
} catch (ExpiredJwtException expiredEx) {
throw new JwtExpiredTokenException("JWT Token expired", expiredEx);
}
}
示例7: loadUserByUsername
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
return userFromDatabase.map(user -> {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(lowercaseLogin,
user.getPassword(),
grantedAuthorities);
}).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
"database"));
}
示例8: testGetExistingAccount
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Test
public void testGetExistingAccount() throws Exception {
Authentication authentication = Mockito.mock(Authentication.class);
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
Mockito.when(authentication.getPrincipal()).thenReturn(new User("user", "pass", authorities));
mock.perform(get("/api/account")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.login").value("user"))
.andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
示例9: prepareUserDetails
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
private UserDetails prepareUserDetails(String jsonUserDetails) throws JsonProcessingException, IOException{
ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(jsonUserDetails);
String userId = root.get("dbUser").get("id").asText();
String username = root.get("username").asText();
boolean isEnabled = root.get("enabled").asBoolean();
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
Iterator<JsonNode> authoritiesIterator = root.get("authorities").elements();
while(authoritiesIterator.hasNext()){
JsonNode authorityNode = authoritiesIterator.next();
authorities.add(new SimpleGrantedAuthority(authorityNode.get("authority").asText()));
}
return new AuthUser(userId, username, authorities, isEnabled);
}
开发者ID:quebic-source,项目名称:microservices-sample-project,代码行数:20,代码来源:CommonAuthenticationTokenFilter.java
示例10: loadUserByUsername
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Override
public AttributedUserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
login = login.toLowerCase(Locale.ROOT);
final SmartiUser smartiUser = getSmaritUser(login);
if (smartiUser == null) {
log.debug("User {} not found", login);
throw new UsernameNotFoundException(String.format("Unknown user: '%s'", login));
}
final MongoUserDetails userDetails = new MongoUserDetails(
smartiUser.getLogin(),
smartiUser.getPassword(),
Collections2.transform(smartiUser.getRoles(),
role -> new SimpleGrantedAuthority("ROLE_" + StringUtils.upperCase(role, Locale.ROOT))
)
);
userDetails.addAttributes(smartiUser.getProfile());
return userDetails;
}
示例11: getAuthentication
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
Collection<? extends GrantedAuthority> authorities =
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
User principal = new User(claims.getSubject(), "",
authorities);
return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
示例12: loadUserByUser
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
public UserDetails loadUserByUser(User targetUser)
throws UsernameNotFoundException {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
resynchronisationUserService.synchronizeUserInfo(targetUser.getEppn());
ldapGroup2UserRoleService.syncUser(targetUser.getEppn());
for(String role : targetUser.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role));
}
return new org.springframework.security.core.userdetails.User(targetUser.getEppn(), "dummy",
true, // enabled
true, // account not expired
true, // credentials not expired
true, // account not locked
authorities);
}
示例13: loadUserByUsername
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
public UserDetails loadUserByUsername(String username) {
SysUser user = userRepository.findByUsername(username);
if (user != null) {
List<SysPermission> permissions = permissionRepository.findByAdminUserId(user.getId());
List<GrantedAuthority> grantedAuthorities = new ArrayList <>();
for (SysPermission permission : permissions) {
if (permission != null && permission.getName()!=null) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
grantedAuthorities.add(grantedAuthority);
}
}
return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
} else {
throw new UsernameNotFoundException("admin: " + username + " do not exist!");
}
}
示例14: loadUserByUsername
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
Optional<User> userFromDatabase = findOneWithAuthoritiesByLogin(login);
return userFromDatabase.map(user -> {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + login + " was not activated");
}
List<GrantedAuthority> grantedAuthorities =
user.getAuthorities()
.stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new RichUserDetails(user.getId(),user.getPhone(),user.getLoginName(),user.getPasswordHash(), grantedAuthorities);
}).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the " +
"database"));
}
示例15: loadUserByUsername
import org.springframework.security.core.authority.SimpleGrantedAuthority; //导入依赖的package包/类
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneByLogin(lowercaseLogin);
return userFromDatabase.map(user -> {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(lowercaseLogin,
user.getPassword(),
grantedAuthorities);
}).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
"database"));
}