本文整理汇总了Java中org.springframework.security.authentication.UsernamePasswordAuthenticationToken.setDetails方法的典型用法代码示例。如果您正苦于以下问题:Java UsernamePasswordAuthenticationToken.setDetails方法的具体用法?Java UsernamePasswordAuthenticationToken.setDetails怎么用?Java UsernamePasswordAuthenticationToken.setDetails使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.springframework.security.authentication.UsernamePasswordAuthenticationToken
的用法示例。
在下文中一共展示了UsernamePasswordAuthenticationToken.setDetails方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doFilterInternal
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String authToken = request.getHeader(this.tokenHeader);
// authToken.startsWith("Bearer ")
// String authToken = header.substring(7);
String username = jwtTokenUtil.getUsernameFromToken(authToken);
logger.info("checking authentication user " + username);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
logger.info("authenticated user " + username + ", setting security context");
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
示例2: doFilter
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String header_authorization = httpServletRequest.getHeader("Authorization");
String token = (StringUtils.isBlank(header_authorization) ? null : header_authorization.split(" ")[1]);
if (StringUtils.isBlank(header_authorization) && token == null) {
logger.info("Token Not found in header.");
} else {
UserDetails principal = null;
try {
principal = authBuilder.getDefaultUserDetailsService().loadUserByUsername(token);
UsernamePasswordAuthenticationToken userAuthenticationToken = new UsernamePasswordAuthenticationToken(
principal, "", principal.getAuthorities());
userAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(userAuthenticationToken);
} catch (Exception e) {
HttpServletResponse httpresposne = (HttpServletResponse) response;
httpresposne.setContentType("application/json");
httpresposne.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
ObjectMapper jsonMapper = new ObjectMapper();
PrintWriter out = httpresposne.getWriter();
Map<String, String> jsonResponse = new HashMap<String, String>();
jsonResponse.put("msg", "Invalid Token");
out.write(jsonMapper.writeValueAsString(jsonResponse));
out.flush();
out.close();
return;
}
chain.doFilter(request, response);
}
}
示例3: attemptAuthentication
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
Optional<? extends AuthenticationRequestBody> requestBody = Try.of(() ->
Optional.ofNullable(new ObjectMapper().readValue(httpServletRequest.getInputStream(),
jwtSecurityProperties.getAuthenticationRequestBody()))
).recover(ex ->
Optional.empty()
).get();
final UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(requestBody.map(AuthenticationRequestBody::getLogin).orElse(null),
requestBody.map(AuthenticationRequestBody::getPassword).orElse(null));
token.setDetails(requestBody.map(AuthenticationRequestBody::isRememberMe));
return getAuthenticationManager().authenticate(token);
}
示例4: 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);
}
示例5: doFilterInternal
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String authToken = request.getHeader(this.tokenHeader);
// authToken.startsWith("Bearer ")
// String authToken = header.substring(7);
String username = jwtTokenUtil.getUsernameFromToken(authToken);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
logger.info("checking authentication for user " + username);
// It is not compelling necessary to load the use details from the database. You could also store the information
// in the token and read it from it. It's up to you ;)
JwtUser userDetails = (JwtUser)this.userDetailsService.loadUserByUsername(username);
// For simple validation it is completely sufficient to just check the token integrity. You don't have to call
// the database compellingly. Again it's up to you ;)
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
logger.info("authenticated user " + username + ", setting security context");
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
示例6: doFilterInternal
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String auth_token = request.getHeader(this.token_header);
final String auth_token_start = "Bearer ";
if (StringUtils.isNotEmpty(auth_token) && auth_token.startsWith(auth_token_start)) {
auth_token = auth_token.substring(auth_token_start.length());
} else {
// 不按规范,不允许通过验证
auth_token = null;
}
String username = jwtUtils.getUsernameFromToken(auth_token);
logger.info(String.format("Checking authentication for user %s.", username));
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// It is not compelling necessary to load the use details from the database. You could also store the information
// in the token and read it from it. It's up to you ;)
// UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
UserDetails userDetails = jwtUtils.getUserFromToken(auth_token);
logger.info(userDetails.getUsername());
// For simple validation it is completely sufficient to just check the token integrity. You don't have to call
// the database compellingly. Again it's up to you ;)
if (jwtUtils.validateToken(auth_token, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
logger.info(String.format("Authenticated user %s, setting security context", username));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(request, response);
}
示例7: authenticate
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
private SubsonicRESTController.ErrorCode authenticate(HttpServletRequest httpRequest, String username, String password, String salt, String token, Authentication previousAuth) {
// Previously authenticated and username not overridden?
if (username == null && previousAuth != null) {
return null;
}
if (salt != null && token != null) {
User user = securityService.getUserByName(username);
if (user == null) {
return SubsonicRESTController.ErrorCode.NOT_AUTHENTICATED;
}
String expectedToken = DigestUtils.md5Hex(user.getPassword() + salt);
if (!expectedToken.equals(token)) {
return SubsonicRESTController.ErrorCode.NOT_AUTHENTICATED;
}
password = user.getPassword();
}
if (password != null) {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
authRequest.setDetails(authenticationDetailsSource.buildDetails(httpRequest));
try {
Authentication authResult = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(authResult);
return null;
} catch (AuthenticationException x) {
eventPublisher.publishEvent(new AuthenticationFailureBadCredentialsEvent(authRequest, x));
return SubsonicRESTController.ErrorCode.NOT_AUTHENTICATED;
}
}
return SubsonicRESTController.ErrorCode.MISSING_PARAMETER;
}
示例8: extractAuthentication
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
Object principal = getPrincipal(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
OAuth2Request request = new OAuth2Request(null, this.clientId, null, true, null,
null, null, null, null);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
示例9: doFilterInternal
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String authHeader = request.getHeader(this.tokenHeader);
if (authHeader != null && authHeader.startsWith(tokenHead)) {
final String authToken = authHeader.substring(tokenHead.length()); // The part after "Bearer "
String account = jwtTokenUtil.getUsernameFromToken(authToken);
logger.info("checking authentication " + account);
if (account != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// 如果我们足够相信token中的数据,也就是我们足够相信签名token的secret的机制足够好
// 这种情况下,我们可以不用再查询数据库,而直接采用token中的数据
// 本例中,我们还是通过Spring Security的 @UserDetailsService 进行了数据查询
// 但简单验证的话,你可以采用直接验证token是否合法来避免昂贵的数据查询
UserDetails userDetails = this.userDetailsService.loadUserByUsername(account);
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
request));
logger.info("authenticated user " + account + ", setting security context");
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
}
chain.doFilter(request, response);
}
示例10: extractAuthentication
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
Object principal = getPrincipal(map);
OAuth2Request request = getRequest(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
示例11: extractAuthentication
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
private OAuth2Authentication extractAuthentication(Map<String, Object> map) {
Object principal = getPrincipal(map);
List<GrantedAuthority> authorities = this.authoritiesExtractor
.extractAuthorities(map);
OAuth2Request request = new OAuth2Request(null, this.clientId, null, true, null,
null, null, null, null);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
principal, "N/A", authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
示例12: additionalAuthenticationChecks
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
authentication.setDetails(userDetails);
}
示例13: doFilter
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
/**
* doFilter
* Perform Authorization Access via Token Validation.
*
* @param request Reference
* @param response Reference
* @param chain Filter Chain
* @throws java.io.IOException Thrown if IO Exceptions.
* @throws javax.servlet.ServletException Thrown if Servlet Exceptions.
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
/**
* Obtain the JWT from the Authorization Header.
*/
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authToken = YourMicroserviceSecurityConstants.obtainAuthorizationBearerToken(httpRequest);
/**
* Now Verify the Token and then, obtain the Subject Claim.
* Validate we have a username from an extracted token and we are not authenticated,
* then determine if the Token can be fully validated and has not Expired.
*/
if (authToken != null) {
try {
JWTClaimsSet jwtClaimsSet = yourMicroserviceToken.verifyToken(authToken);
if (jwtClaimsSet != null) {
/**
* Obtain our Subject from the Claims Set, which is our UserName, aka Your Microservice Person's
* Primary Email.
*/
String username = jwtClaimsSet.getSubject();
if (username != null && !username.isEmpty() &&
SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
/**
* Perform Statistical Metric of a Token being Used.
*/
Integer countUpdated =
identityProviderEntityManager.incrementTokenHistoryUsage(jwtClaimsSet.getJWTID());
if (countUpdated == null || countUpdated != 1) {
/**
* We did not update the Usage Counter, this indicates that either the
* Token has Expired, Revoked or in some other state other than Active,
* so, immediately fail this token.
*/
SecurityContextHolder.getContext().setAuthentication(null);
}
}
}
} catch (YourMicroserviceInvalidTokenException iste) {
/**
* Do Nothing, as the attempt of the failed Token will be Denied...
*/
SecurityContextHolder.getContext().setAuthentication(null);
YourMicroserviceToken.LOGGER.warn("{}Invalid Token Denying Access.", YourMicroserviceToken.LOGGING_HEADER);
}
}
/**
* Continue filter chain.
*/
chain.doFilter(request, response);
}
示例14: doFilterInternal
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
@Override
protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response ,
FilterChain chain ) throws ServletException, IOException {
final String authToken = this.extractAuthTokenFromRequest( request , this.tokenHeader );
final String username = jwtTokenUtil.getUsernameFromToken( authToken );
LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , username );
if ( username != null && SecurityContextHolder.getContext().getAuthentication() == null ) {
// 对于简单的验证,只需检查令牌的完整性即可。 您不必强制调用数据库。 由你自己决定
// 是否查询数据看情况,目前是查询数据库
UserDetails userDetails = this.userDetailsService.loadUserByUsername( username );
if ( jwtTokenUtil.validateToken( authToken , userDetails ) ) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken( userDetails , null , userDetails.getAuthorities() );
ThreadContext.put( USER_ID , String.valueOf( ( ( BasicJwtUser ) userDetails ).getId() ) );
ThreadContext.put( USER_NAME , username );
authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails( request ) );
LogUtils.getLogger().debug( "authToken : {},username : {}" , authToken , username );
LogUtils.getLogger().debug( "该 " + username + "用户已认证, 设置安全上下文" );
SecurityContextHolder.getContext().setAuthentication( authentication );
}
}
chain.doFilter( request , response );
ThreadContext.clearAll();
}
示例15: doFilterInternal
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入方法依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String authorization = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);
/**
* Whenever the user wants to access a protected route or resource,
* the user agent should send the JWT,
* typically in the Authorization header using the Bearer schema.
* The content of the header should look like the following:
* Authorization: Bearer <token>
* This is a stateless authentication mechanism as the user state is never saved in server memory.
* The server's protected routes will check for a valid JWT in the Authorization header,
* and if it's present, the user will be allowed to access protected resources.
*/
// authToken.startsWith("Bearer ")
// String authToken = header.substring(7);
if (StringUtils.isBlank(authorization)) {
filterChain.doFilter(httpServletRequest, httpServletResponse);
return;
}
try {
String username = jwtTokenUtil.getUsernameFromToken(authorization);
LOGGER.info("checking authentication for user:{},uri:{}", username, httpServletRequest.getRequestURI());
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {//服务器重启的场景
// It is not compelling necessary to load the use details from the database. You could also store the information
// in the token and read it from it. It's up to you ;)
//validateToken的逻辑中,就需要判断username是否存在和过期时间
//查出来UserDetails类型的数据是因为UsernamePasswordAuthenticationToken对象会使用
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
// For simple validation it is completely sufficient to just check the token integrity. You don't have to call
// the database compellingly. Again it's up to you ;)
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
LOGGER.info("authenticated user {}, setting security context", username);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
} catch (Exception e) {
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
try (PrintWriter out = httpServletResponse.getWriter()) {
out.write(JSON.toJSONString("unauthorized"));
out.flush();
}
}
}