本文整理汇总了Java中org.springframework.security.authentication.UsernamePasswordAuthenticationToken类的典型用法代码示例。如果您正苦于以下问题:Java UsernamePasswordAuthenticationToken类的具体用法?Java UsernamePasswordAuthenticationToken怎么用?Java UsernamePasswordAuthenticationToken使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
UsernamePasswordAuthenticationToken类属于org.springframework.security.authentication包,在下文中一共展示了UsernamePasswordAuthenticationToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getAuthentication
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
public Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
// parse the token.
String user = getUsername(token);
String roles = getBody(token).get("roles", String.class);
List<GrantedAuthority> grantedAuths =
AuthorityUtils.commaSeparatedStringToAuthorityList(roles);
return user != null ?
new UsernamePasswordAuthenticationToken(user, null,
grantedAuths) :
null;
}
return null;
}
示例2: authenticate
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
String email = token.getName();
CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
if(user == null) {
throw new UsernameNotFoundException("Invalid username/password");
}
// Database Password already encrypted:
String password = user.getPassword();
boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);
if(!passwordsMatch) {
throw new BadCredentialsException("Invalid username/password");
}
Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
return usernamePasswordAuthenticationToken;
}
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:21,代码来源:CalendarUserAuthenticationProvider.java
示例3: handleUsernameTokenPrincipal
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback) throws IOException,
UnsupportedCallbackException {
UserDetails user = loadUserDetails(callback.getPrincipal().getName());
WSUsernameTokenPrincipal principal = callback.getPrincipal();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
principal, principal.getPassword(), user.getAuthorities());
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authRequest.toString());
}
SecurityContextHolder.getContext().setAuthentication(authRequest);
if (user instanceof IUser) {
HttpSession session=ContextHolder.getHttpSession();
session.setAttribute(ContextHolder.LOGIN_USER_SESSION_KEY, user);
session.setAttribute(ContextHolder.USER_LOGIN_WAY_KEY,IWebservice.WS_LOGIN_WAY);
}
}
示例4: login
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@ApiOperation(value = "Login")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public boolean login(@RequestBody User user, HttpServletRequest request) {
User u = this.userService.login(user.getUsername(), user.getPassword());
if (u != null) {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
user.getUsername(), user.getPassword());
// Authenticate the user
Authentication authentication = authenticationManager.authenticate(authRequest);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
// Create a new session and add the security context.
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
return true;
}
return false;
}
示例5: authorize
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@PostMapping("/authenticate")
@Timed
public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
try {
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
return ResponseEntity.ok(new JWTToken(jwt));
} catch (AuthenticationException ae) {
log.trace("Authentication exception trace: {}", ae);
return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",
ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
}
}
示例6: authorize
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
@Timed
public ResponseEntity<?> authorize(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword());
try {
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginDTO.isRememberMe() == null) ? false : loginDTO.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
return ResponseEntity.ok(new JWTToken(jwt));
} catch (AuthenticationException exception) {
return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
}
}
示例7: attemptAuthentication
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
User creds = new ObjectMapper()
.readValue(req.getInputStream(), User.class);
List<Role> authorities = new ArrayList<>();
authorities.add(Role.ROLE_MANAGER);
authorities.add(Role.ROLE_EMPLOYE);
authorities.add(Role.ROLE_ADMIN);
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getMatricule(),
creds.getPassword(),
Collections.emptyList()
)
);
}
示例8: doFilterInternal
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String token = request.getHeader(AUTH_HEADER);
if (token != null && token.startsWith(BEARER_PREFIX)) {
token = token.substring(7);
}
String username = jwtTokenUtil.getUsernameFromToken(token);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.tokenValido(token)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
示例9: loginHelp
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
private MyUser loginHelp(MyUser user, String passwd, HttpSession session) {
if (user.getUserId() != null) {
String encryptedPassword;
try {
encryptedPassword = this.passwordEncryption.getEncryptedPassword(passwd, user.getSalt());
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
return new MyUser();
}
if (user.getPassword().equals(encryptedPassword)) {
if(session != null) {
Authentication auth =
new UsernamePasswordAuthenticationToken(user.getUserId(), user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
session.setAttribute(WebUtils.SECURITYCONTEXT, SecurityContextHolder.getContext());
}
user.setPassword("XXX");
return user;
}
}
session.invalidate();
return new MyUser();
}
示例10: getAuthentication
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(jwtProperties.getToken().getSecret())
.parseClaimsJws(token)
.getBody();
Collection<? extends GrantedAuthority> authorities =
Try.of(() ->
Arrays.stream(claims.get(jwtProperties.getToken().getPayload().getAuthoritiesKey()).toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList())
).recover(ex ->
Collections.emptyList()
).get();
User principal = new User(claims.getSubject(), "", authorities);
return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
示例11: attemptAuthentication
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (!HttpMethod.POST.name().equals(request.getMethod()) || !WebUtil.isAjax(request)) {
if(logger.isDebugEnabled()) {
logger.debug("Authentication method not supported. Request method: " + request.getMethod());
}
throw new AuthMethodNotSupportedException("Authentication method not supported");
}
LoginRequest loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class);
if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) {
throw new AuthenticationServiceException("Username or Password not provided");
}
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
return this.getAuthenticationManager().authenticate(token);
}
示例12: authenticate
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
private void authenticate ()
{
String name = "userTest";
Set<GrantedAuthority> roles = new HashSet<> ();
roles.add (new SimpleGrantedAuthority (Role.DOWNLOAD.getAuthority ()));
roles.add (new SimpleGrantedAuthority (Role.SEARCH.getAuthority ()));
roles.add (
new SimpleGrantedAuthority (Role.DATA_MANAGER.getAuthority ()));
SandBoxUser user = new SandBoxUser (name, name, true, 0, roles);
Authentication auth = new UsernamePasswordAuthenticationToken (
user, user.getPassword (), roles);
SecurityContextHolder.getContext ().setAuthentication (auth);
logger.info ("userTest roles: " + auth.getAuthorities ());
}
示例13: testDoFilterInternal
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Test
public void testDoFilterInternal() throws IOException, ServletException {
JwtPayloadHelper payload = new JwtPayloadHelper()
.withName(JwtAuthorizationFilter.ORG_NAME)
.withOrgType(ORG_TYPE);
request.addHeader("Authorization", JwtTestHelper.createJwt(payload));
JwtAuthorizationFilter testJwtAuthFilter = new JwtAuthorizationFilter(authenticationManager);
PowerMockito.mockStatic(SecurityContextHolder.class);
SecurityContext mockSecurityContext = PowerMockito.mock(SecurityContext.class);
PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(mockSecurityContext);
testJwtAuthFilter.doFilterInternal(request, response, filterChain);
verify(filterChain, times(1)).doFilter(any(MockHttpServletRequest.class), any(MockHttpServletResponse.class));
verify(SecurityContextHolder.getContext(), times(1)).setAuthentication(any(UsernamePasswordAuthenticationToken.class));
}
示例14: testDoFilterInternalWithInvalidOrgName
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Test
public void testDoFilterInternalWithInvalidOrgName() throws IOException, ServletException {
JwtPayloadHelper payload = new JwtPayloadHelper()
.withName("invalid-name")
.withOrgType(ORG_TYPE);
request.addHeader("Authorization", JwtTestHelper.createJwt(payload));
JwtAuthorizationFilter testJwtAuthFilter = new JwtAuthorizationFilter(authenticationManager);
PowerMockito.mockStatic(SecurityContextHolder.class);
SecurityContext mockSecurityContext = PowerMockito.mock(SecurityContext.class);
PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(mockSecurityContext);
testJwtAuthFilter.doFilterInternal(request, response, filterChain);
verify(filterChain, times(1)).doFilter(any(MockHttpServletRequest.class), any(MockHttpServletResponse.class));
verify(SecurityContextHolder.getContext(), times(0)).setAuthentication(any(UsernamePasswordAuthenticationToken.class));
}
示例15: signin
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
public String signin(String username, String password) {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
return jwtTokenProvider.createToken(username, userRepository.findByUsername(username).getRoles());
} catch (AuthenticationException e) {
throw new CustomException("Invalid username/password supplied", HttpStatus.UNPROCESSABLE_ENTITY);
}
}