Java Code Examples for org.springframework.security.authentication.UsernamePasswordAuthenticationToken#setDetails()
The following examples show how to use
org.springframework.security.authentication.UsernamePasswordAuthenticationToken#setDetails() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JwtAuthenticationTokenFilter.java From sctalk with Apache License 2.0 | 7 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authHeader = request.getHeader("Authorization"); String tokenHead = "Bearer "; if (authHeader != null && authHeader.startsWith(tokenHead)) { String authToken = authHeader.substring(tokenHead.length()); String username = jwtTokenUtil.getUsernameFromToken(authToken); 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)); SecurityContextHolder.getContext().setAuthentication(authentication); } } } chain.doFilter(request, response); }
Example 2
Source File: JwtAuthFilter.java From spring-boot-react-blog with Apache License 2.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = getJwtFromRequest(request); if (StringUtils.hasText(jwt) && jwtUtil.validateToken(jwt)) { String userId = jwtUtil.getUserIdFromToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(userId); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception ex) { logger.error("Could not set user authentication in security context", ex); } filterChain.doFilter(request, response); }
Example 3
Source File: JwtAuthenticationTokenFilter.java From mall-learning with Apache License 2.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authHeader = request.getHeader(this.tokenHeader); if (authHeader != null && authHeader.startsWith(this.tokenHead)) { String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer " String username = jwtTokenUtil.getUserNameFromToken(authToken); LOGGER.info("checking username:{}", 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); SecurityContextHolder.getContext().setAuthentication(authentication); } } } chain.doFilter(request, response); }
Example 4
Source File: JwtAuthenticationTokenFilter.java From mall-learning with Apache License 2.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authHeader = request.getHeader(this.tokenHeader); if (authHeader != null && authHeader.startsWith(this.tokenHead)) { String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer " String username = jwtTokenUtil.getUserNameFromToken(authToken); LOGGER.info("checking username:{}", 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); SecurityContextHolder.getContext().setAuthentication(authentication); } } } chain.doFilter(request, response); }
Example 5
Source File: UserFilter.java From WeEvent with Apache License 2.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String url = request.getRequestURI(); if (!urlSet.contains(url)) { String token = request.getHeader(JwtUtils.AUTHORIZATION_HEADER_PREFIX); String privateSecret = GovernanceApplication.governanceConfig.getPrivateSecret(); if (!StringUtils.isBlank(token) && JwtUtils.verifierToken(token, privateSecret)) { AccountEntity accountEntity = JwtUtils.decodeToken(token, privateSecret); if (accountEntity != null) { log.info("get token from HTTP header, {} : {}", JwtUtils.AUTHORIZATION_HEADER_PREFIX, token); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(accountEntity.getUsername(), null, null); auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(auth); } } filterChain.doFilter(request, response); } else { String newPath = url.replace("/weevent-governance", ""); RequestDispatcher requestDispatcher = request.getRequestDispatcher(newPath); requestDispatcher.forward(request, response); } }
Example 6
Source File: JwtAuthenticationFilter.java From Spring-Boot-Blog-REST-API with GNU Affero General Public License v3.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try{ String jwt = getJwtFromRequest(request); if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)){ Long userId = tokenProvider.getUserIdFromJWT(jwt); UserDetails userDetails = customUserDetailsService.loadUserById(userId); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } } catch (Exception ex){ LOGGER.error("Could not set user authentication in security context", ex); } filterChain.doFilter(request, response); }
Example 7
Source File: JwtAuthTokenFilter.java From TASK-Management-System with MIT License | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = getJwt(request); if (jwt != null && tokenProvider.validateJwtToken(jwt)) { String username = tokenProvider.getUserNameFromJwtToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception e) { logger.error("Can NOT set user authentication -> Message: {}", e); } filterChain.doFilter(request, response); }
Example 8
Source File: JwtAuthenticationTokenFilter.java From mall with Apache License 2.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authHeader = request.getHeader(this.tokenHeader); if (authHeader != null && authHeader.startsWith(this.tokenHead)) { String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer " String username = jwtTokenUtil.getUserNameFromToken(authToken); LOGGER.info("checking username:{}", 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); SecurityContextHolder.getContext().setAuthentication(authentication); } } } chain.doFilter(request, response); }
Example 9
Source File: UserDetailsAuthenticationProviderImpl.java From spring-backend-boilerplate with Apache License 2.0 | 6 votes |
/** * Implementation of an abstract method defined in the base class. The * retrieveUser() method is called by authenticate() method of the base * class. The latter is called by the AuthenticationManager. */ @Override protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails details; try { details = this.getUserDetailsService().loadUserByUsername(username); authentication.setDetails(details); } catch (DataAccessException repositoryProblem) { throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } if (details == null) { throw new AuthenticationServiceException( "UserDetailsService returned null, which is an interface contract violation"); } return details; }
Example 10
Source File: JwtAuthenticationFilter.java From MovieApp with MIT License | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { // Get jwt token String jwt = getJwtFromRequest(request); // Validate the token if (StringUtils.hasText(jwt) && tokenValidator.validateToken(jwt)) { // Build userDetails UserDetails userDetails = tokenValidator.getUserPrincipalFromJWT(jwt); // Crate auth object UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); // Authenticate the user SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception ex) { logger.error("Could not set user authentication in security context", ex); // In case of failure. Make sure it's clear; so guarantee user won't be authenticated. SecurityContextHolder.clearContext(); } filterChain.doFilter(request, response); }
Example 11
Source File: JwtLoginFilter.java From SpringSecurity-JWT-Vue-Deom with MIT License | 6 votes |
/** * 提取用户账号密码进行验证 * */ @Override public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException { // 判断是否要抛出 登陆请求过快的异常 loginCountService.judgeLoginCount(httpServletRequest); // 获取 User 对象 // readValue 第一个参数 输入流,第二个参数 要转换的对象 User user = new ObjectMapper().readValue(httpServletRequest.getInputStream(), User.class); // 验证码验证 verifyCodeService.verify(httpServletRequest.getSession().getId(), user.getVerifyCode()); // 对 html 标签进行转义,防止 XSS 攻击 String username = user.getUsername(); username = HtmlUtils.htmlEscape(username); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( username, user.getPassword(), user.getAuthorities() ); // 添加验证的附加信息 // 包括验证码信息和是否记住我 token.setDetails(new LoginDetails(user.getRememberMe(), user.getVerifyCode())); // 进行登陆验证 return getAuthenticationManager().authenticate(token); }
Example 12
Source File: AppUserInfoTokenServices.java From template-spring-boot-oauth2-wso2-is with Apache License 2.0 | 5 votes |
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); }
Example 13
Source File: DiscordTokenServices.java From JuniperBot with GNU General Public License v3.0 | 5 votes |
public OAuth2Authentication load(String accessToken) { Map map = executeRequest(Map.class, apiProperties.getDiscord().getUserInfoUri(), accessToken); Object principal = map.get("username"); principal = (principal == null ? "unknown" : principal); List<GrantedAuthority> authorities = authoritiesExtractor.extractAuthorities(map); OAuth2Request request = new OAuth2Request(null, apiProperties.getDiscord().getClientId(), null, true, null, null, null, null, null); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( principal, "N/A", authorities); token.setDetails(DiscordUserDetails.create(map)); return new OAuth2Authentication(request, token); }
Example 14
Source File: CustomUserInfoTokenServices.java From DAFramework with MIT License | 5 votes |
private OAuth2Authentication extractAuthentication(Map<String, Object> map) { Object principal = getPrincipal(map); OAuth2Request request = getRequest(map); List<GrantedAuthority> authorities = authoritiesExtractor.extractAuthorities(map); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "N/A", authorities); token.setDetails(map); return new OAuth2Authentication(request, token); }
Example 15
Source File: JwtAuthenticationTokenFilter.java From RuoYi-Vue with MIT License | 5 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { LoginUser loginUser = tokenService.getLoginUser(request); if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) { tokenService.verifyToken(loginUser); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } chain.doFilter(request, response); }
Example 16
Source File: TokenFilter.java From BlogManagePlatform with Apache License 2.0 | 5 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { if (Matcher.needVerify(request)) { String token = TokenUtil.getRealToken(request); UserDetails user; try { user = TokenUtil.verify(token); } catch (TokenExpiredException e) { //如果token超时失效,这里不删除token,而是直接返回,并告诉客户端token失效,让客户端重新登陆. ServletUtil.writeJson(response, Result.expired()); return; } if (user != null && SecurityContextHolder.getContext().getAuthentication() == null) { if (!idTokenCache.exist(token)) { //如果缓存中不存在用户,则说明被下线 ServletUtil.writeJson(response, Result.notLogin("该用户已被下线,请重新登录")); return; } //如果成功取出信息且上下文中无验证信息,则设置验证信息 //这里要设置权限,和frodez.config.security.user.UserDetailsServiceImpl.loadUserByUsername(String username) //和frodez.config.security.auth.AuthorityManager.decide(Authentication auth, Object object, Collection<ConfigAttribute> permissions)对应 UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); authentication.setDetails(new WebAuthenticationDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } chain.doFilter(request, response); }
Example 17
Source File: UserServiceIntTest.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 5 votes |
private OAuth2Authentication createMockOAuth2AuthenticationWithDetails(Map<String, Object> userDetails) { Set<String> scopes = new HashSet<String>(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(Constants.ANONYMOUS_USER, Constants.ANONYMOUS_USER, authorities); usernamePasswordAuthenticationToken.setDetails(userDetails); OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null, null); return new OAuth2Authentication(authRequest, usernamePasswordAuthenticationToken); }
Example 18
Source File: UserControllerTest.java From kylin with Apache License 2.0 | 4 votes |
private void logInWithUser(ManagedUser user) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()); token.setDetails(SecurityContextHolder.getContext().getAuthentication().getDetails()); SecurityContextHolder.getContext().setAuthentication(token); }
Example 19
Source File: RestLoginAuthenticationFilter.java From uexam-mysql with GNU Affero General Public License v3.0 | 4 votes |
private void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); }
Example 20
Source File: SessionServiceImpl.java From putnami-web-toolkit with GNU Lesser General Public License v3.0 | 4 votes |
@Override public SessionDto signIn(SigninDto request) { String username = request.getUsername(); String password = request.getPassword(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); authRequest.setDetails(new WebAuthenticationDetails(RequestThreadLocalUtils.getRequest())); Authentication authResponse = authenticationManager.authenticate(authRequest); SecurityContextHolder.getContext().setAuthentication(authResponse); return getCurrentSession(); }