下面列出了怎么用org.springframework.security.core.userdetails.User的API类实例代码及写法,或者点击链接到github查看源代码。
Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(token)
.getBody();
// fix bug: 当前用户如果没有任何权限时,在输入用户名后,刷新验证码会抛IllegalArgumentException
Object authoritiesStr = claims.get(AUTHORITIES_KEY);
Collection<? extends GrantedAuthority> authorities =
ObjectUtil.isNotEmpty(authoritiesStr) ?
Arrays.stream(authoritiesStr.toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList()) : Collections.emptyList();
User principal = new User(claims.getSubject(), "", authorities);
return new UsernamePasswordAuthenticationToken(principal, token, authorities);
}
/**
* Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
* {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
* application Spring Security usernames are email addresses).
*/
@Override
public CalendarUser getCurrentUser() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
if (authentication == null) {
return null;
}
User user = (User)authentication.getPrincipal();
String email = user.getUsername();
// String email = user.getEmail();
if (email == null) {
return null;
}
CalendarUser result = calendarService.findUserByEmail(email);
if (result == null) {
throw new IllegalStateException(
"Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
}
return result;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (StringUtils.isBlank(username)){
throw new UserAuthenticationException("用户名或密码不正确");
}
com.beautifulsoup.chengfeng.pojo.User user ;
user= userMapper.selectByNicknameAndPassword(username);
if(null==user){
throw new UserAuthenticationException("用户不存在,登陆失败");
}
return User.builder().username(user.getNickname())
.password(user.getCryptPassword().getCryptPassword()).authorities("/admin").build();
}
@Test
public void testResolveArgument() throws Exception {
// given
ModelAndViewContainer mavContainer = mock(ModelAndViewContainer.class);
WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
NativeWebRequest webRequest = mock(NativeWebRequest.class);
User stubUser = new User(USER_NAME, "", Collections.emptyList());
Principal stubPrincipal = new UsernamePasswordAuthenticationToken(stubUser, null);
when(webRequest.getUserPrincipal()).thenReturn(stubPrincipal);
// when/then
assertEquals(stubUser,
resolver.resolveArgument(validParam, mavContainer, webRequest,binderFactory));
assertEquals(WebArgumentResolver.UNRESOLVED,
resolver.resolveArgument(notAnnotatedParam, mavContainer, webRequest,binderFactory));
assertEquals(WebArgumentResolver.UNRESOLVED,
resolver.resolveArgument(wrongTypeParam, mavContainer, webRequest,binderFactory));
}
@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));
}
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
final String username = authentication.getName();
final String password = authentication.getCredentials().toString();
User user = null;
try {
user = userService.doesUserExist(username);
} catch (UserNotFoundException e) {
}
if (user == null || !user.getEmail().equalsIgnoreCase(username)) {
throw new BadCredentialsException("Username not found.");
}
if (!password.equals(user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
if(user.getRole() == 1) {
authorities.add(new SimpleGrantedAuthority("ROLE_DOCTOR"));
} else {
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
}
final UserDetails principal = new org.springframework.security.core.userdetails.User(username, password, authorities);
return new UsernamePasswordAuthenticationToken(principal, password, authorities);
}
public Object loadUserBySAML(SAMLCredential credential)
throws UsernameNotFoundException {
// The method is supposed to identify local account of user referenced by
// data in the SAML assertion and return UserDetails object describing the user.
String userID = credential.getNameID().getValue();
LOG.info(userID + " is logged in");
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
authorities.add(authority);
// In a real scenario, this implementation has to locate user in a arbitrary
// dataStore based on information present in the SAMLCredential and
// returns such a date in a form of application specific UserDetails object.
return new User(userID, "<abc123>", true, true, true, true, authorities);
}
/**
* Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
* {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
* application Spring Security usernames are email addresses).
*/
@Override
public CalendarUser getCurrentUser() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
if (authentication == null) {
return null;
}
User user = (User)authentication.getPrincipal();
String email = user.getUsername();
// String email = user.getEmail();
if (email == null) {
return null;
}
CalendarUser result = calendarService.findUserByEmail(email);
if (result == null) {
throw new IllegalStateException(
"Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
}
return result;
}
@Override
public void onLoginSuccess(Authentication authentication, HttpServletResponse response) throws IOException {
log.debug("Login successed, generating jwtToken...");
User user = (User) authentication.getPrincipal();
String jwtToken = jwtTokenHelper.generateToken(user.getUsername());
if(jwtSecurityProps.getCookieStrategy().isEnabled()) {
Cookie authCookie = new Cookie(jwtSecurityProps.getCookieStrategy().getCookie(), jwtToken);
authCookie.setHttpOnly(true);
authCookie.setMaxAge((int) jwtSecurityProps.getExpirationInSec());
authCookie.setPath(contextPath);
response.addCookie(authCookie);
log.debug("Set jwtToken into the cookie {}", jwtSecurityProps.getCookieStrategy().getCookie());
}
if(jwtSecurityProps.getHeaderStrategy().isEnabled()) {
jwtTokenHelper.setHeader(response, jwtToken);
log.debug("Set jwtToken into the response header {}", jwtSecurityProps.getHeaderStrategy().getHeader());
}
UserTokenState userTokenState = new UserTokenState(jwtToken, jwtSecurityProps.getExpirationInSec());
String jwtResponse = objectMapper.writeValueAsString(userTokenState);
response.setContentType("application/json");
response.getWriter().write(jwtResponse);
}
@Bean
public ReactiveUserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails admin = User
.withUsername("admin")
.password(passwordEncoder.encode("admin12345678"))
.roles("ADMIN", "MEMBER")
.build();
UserDetails caterpillar = User
.withUsername("caterpillar")
.password(passwordEncoder.encode("12345678"))
.roles("MEMBER")
.build();
return new MapReactiveUserDetailsService(admin, caterpillar);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
CustomUserDetails userDetails = userRepository.getUser(username);
if (userDetails == null) {
LOGGER.warn("{} not exist.", username);
throw new UsernameNotFoundException(username + " not exists");
}
return new User(
userDetails.getUsername(),
userDetails.getPassword(),
userDetails.getAccountEnabled(),
userDetails.generateAccountNonExpired(),
userDetails.generateCredentialsNonExpired(),
!userDetails.getAccountLocked(),
userDetails.generateAuthorities());
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain, Authentication authentication) {
var user = ((User) authentication.getPrincipal());
var roles = user.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
var signingKey = SecurityConstants.JWT_SECRET.getBytes();
var token = Jwts.builder()
.signWith(Keys.hmacShaKeyFor(signingKey), SignatureAlgorithm.HS512)
.setHeaderParam("typ", SecurityConstants.TOKEN_TYPE)
.setIssuer(SecurityConstants.TOKEN_ISSUER)
.setAudience(SecurityConstants.TOKEN_AUDIENCE)
.setSubject(user.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 864000000))
.claim("rol", roles)
.compact();
response.addHeader(SecurityConstants.TOKEN_HEADER, SecurityConstants.TOKEN_PREFIX + token);
}
/**
* Since we are using multiple {@link AuthenticationProvider}s, make sure to convert the
* authentication principal to proper {@link OneOpsUser} type.
*
* @param req http request.
* @param res http response.
* @param authentication authentication object
* @throws IOException
* @throws ServletException
*/
@Override
public void onAuthenticationSuccess(
HttpServletRequest req, HttpServletResponse res, Authentication authentication)
throws IOException, ServletException {
User principal = (User) authentication.getPrincipal();
OneOpsUser user;
if (principal instanceof OneOpsUser) {
user = (OneOpsUser) principal;
} else {
user = getOneOpsUser(principal);
}
String token = tokenService.generateToken(user);
auditLog.log(new Event(GENERATE_TOKEN, user.getUsername(), user.getDomain().getType(), "N/A"));
LoginResponse loginResponse =
new LoginResponse(token, tokenService.getTokenType(), tokenService.getExpiresInSec());
res.setStatus(HttpStatus.CREATED.value());
res.setContentType(APPLICATION_JSON_VALUE);
mapper.writeValue(res.getWriter(), loginResponse);
clearAuthenticationAttributes(req);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Collection<GrantedAuthority> authorities = new ArrayList<>();
// 从数据库中取出用户信息
SysUser user = userService.selectByName(username);
// 判断用户是否存在
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
}
// 添加权限
List<SysUserRole> userRoles = userRoleService.listByUserId(user.getId());
for (SysUserRole userRole : userRoles) {
SysRole role = roleService.selectById(userRole.getRoleId());
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
// 返回UserDetails实现类
return new User(user.getName(), user.getPassword(), authorities);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//查询用户
SysUserVo sysUserVo = sysUserService.findByLoginName(username).getData();
//查询权限
List<SysUserAuthorityVo> sysUserAuthorityVoList = sysUserAuthorityService.findByUserId(sysUserVo.getUserId()).getData();
StringBuilder authorityList = new StringBuilder();
for (int i = 0; i < sysUserAuthorityVoList.size(); i++) {
SysUserAuthorityVo sysUserAuthorityVo = sysUserAuthorityVoList.get(i);
authorityList.append(sysUserAuthorityVo.getSysAuthority().getAuthorityName());
if (i != sysUserAuthorityVoList.size() - 1) {
authorityList.append(",");
}
}
//查无此用户
if(StringUtils.isEmpty(sysUserVo.getUserId())){
sysUserVo.setLoginName("查无此用户");
sysUserVo.setPassword("查无此用户");
}
// 封装用户信息,并返回。参数分别是:用户名,密码,用户权限
return new User(sysUserVo.getLoginName(), sysUserVo.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(authorityList.toString()));
}
@Override
public boolean addACLToCurrentUser(String name){
if(listTopics().contains(name)) {
String zkServers = environment.getProperty(MetronRestConstants.ZK_URL_SPRING_PROPERTY);
User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String user = principal.getUsername();
List<String> cmd = new ArrayList<>();
cmd.add("--add");
cmd.add("--allow-principal");
cmd.add("User:" + user);
cmd.add("--topic");
cmd.add(name);
cmd.add("--authorizer-properties");
cmd.add("zookeeper.connect=" + String.join(",", zkServers));
AclCommand.main(cmd.toArray(new String[cmd.size()]));
} else {
return false;
}
return true;
}
@Bean
public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() {
return new RoadWebSecurityConfigurerAdapter() {
@SuppressWarnings("deprecation")
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser(
User.withDefaultPasswordEncoder().username("user").password("pass").authorities("ROLE_USER"));
}
};
}
@Bean
public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() {
return new RoadWebSecurityConfigurerAdapter() {
@SuppressWarnings("deprecation")
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser(
User.withDefaultPasswordEncoder().username("user").password("pass").authorities("ROLE_USER"));
}
};
}
@WithMockUser(username = "systemUser")
@Test
void testGetSecurityContextsNoUserThreadNoUserSessions() {
Object user = when(mock(User.class).getUsername()).thenReturn("user").getMock();
assertEquals(
emptyList(),
principalSecurityContextRegistryImpl.getSecurityContexts(user).collect(toList()));
}
private UserDetails loadBarUserDetails(String username) {
Response response = userService.loadBarUser(username);
if (logger.isDebugEnabled())
logger.debug("Loaded from bar details: " + response);
if (response.isOk()) {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("BAR_READ"));
authorities.add(new SimpleGrantedAuthority("BAR_WRITE"));
return new User(username, "", authorities);
}
return null;
}
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(key)
.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, token, authorities);
}
@Bean
ReactiveUserDetailsService authentication() {
return new MapReactiveUserDetailsService(
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build()
);
}
@GetMapping(value = "/token",produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseResult getUserToken(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
log.info(authentication.getName());
log.info(authentication.getAuthorities().toString());
log.info(((User)authentication.getPrincipal()).getPassword());
Map<String,Object> tokenInfo= Maps.newHashMap();
tokenInfo.put("name",authentication.getName());
tokenInfo.put("password",((User)authentication.getPrincipal()).getPassword());
tokenInfo.put("authorities",authentication.getAuthorities());
// Multimap<String,Object> stringObjectMultimap=Multimaps.new
return ResponseResult.createBySuccess(tokenInfo);
}
public CustomUserDetailsService() {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
UserDetails user = User.withUsername("user").password(passwordEncoder.encode("123456")).authorities(WebSecurityConfig.USER).build();
UserDetails admin = User.withUsername("admin").password(passwordEncoder.encode("123456")).authorities(WebSecurityConfig.ADMIN).build();
userList.add(user);
userList.add(admin);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
ResourceOwner resourceOwner = repository.findByUsername(username)
.orElseThrow(() -> new RuntimeException());
return new User(resourceOwner.getUsername(),
resourceOwner.getPassword(),
new ArrayList<>());
}
public User parseUserFromToken(String token) {
String username = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
return userService.loadUserByUsername(username);
}
/**
* The parent method from {@link WebSecurityConfigurerAdapter} (public UserDetailsService userDetailsService())
* originally returns a {@link UserDetailsService}, but this needs to be a {@link UserDetailsManager}
* UserDetailsManager vs UserDetailsService
*/
@Bean
@Override
public UserDetailsManager userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("user").password("password").roles("USER").build());
manager.createUser(User.withUsername("admin").password("admin").roles("USER", "ADMIN").build());
manager.createUser(User.withUsername("[email protected]").password("user1").roles("USER").build());
manager.createUser(User.withUsername("[email protected]").password("admin1").roles("USER", "ADMIN").build());
return manager;
}
@SuppressWarnings({ "squid:S1166" })
private static UserDetails loadUserByUsername(final String username) {
final UserDetailsService userDetailsService = SpringContextHelper.getBean(UserDetailsService.class);
try {
return userDetailsService.loadUserByUsername(username);
} catch (final UsernameNotFoundException e) {
return new User(username, "", Collections.emptyList());
}
}
@Bean
UserDetailsService userDetailsService() {
return username -> {
log.debug("Searching user: {}", username);
if (username.length() > 10) {
throw new UsernameNotFoundException("Could not find user!");
}
final List<SimpleGrantedAuthority> authorities =
Arrays.asList(new SimpleGrantedAuthority("ROLE_" + username.toUpperCase()));
return new User(username, passwordEncoder().encode(username), authorities);
};
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
Optional<Account> accountOptional = accountService.getAccountByUsername(username);
Account account = accountOptional.orElseThrow(() -> new UsernameNotFoundException("Username not found."));
return User.builder()
.username(account.getUsername())
.password(account.getPassword())
.accountExpired(account.isAccountExpired())
.accountLocked(account.isAccountLocked())
.credentialsExpired(account.isCredentialsExpired())
.disabled(!account.isEnabled())
.roles(account.getRoles().stream().map(Enum::toString).toArray(String[]::new)).build();
}