org.springframework.security.authentication.UsernamePasswordAuthenticationToken Java Examples
The following examples show how to use
org.springframework.security.authentication.UsernamePasswordAuthenticationToken.
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 HIS with Apache License 2.0 | 9 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 #2
Source File: MockAuthenticationManager.java From tutorials with MIT License | 8 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName()); if(userDetails == null || !passwordEncoder.matches(authentication.getCredentials().toString(), userDetails.getPassword())) { throw new BadCredentialsException("Invalid username/password"); } UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( authentication.getPrincipal().toString(), authentication.getCredentials().toString(), ROLES); return token; }
Example #3
Source File: SmsStaffServiceImpl.java From HIS with Apache License 2.0 | 8 votes |
@Override public String login(String username, String password) { String token = null; //密码需要客户端加密后传递 try { UserDetails userDetails = userDetailsService.loadUserByUsername(username);//返回的是一个userDetails的实现类AdminUserDetails if(!passwordEncoder.matches(password,userDetails.getPassword())){ //password是从前端过来未经过编译的,而userDetails.getPassword()是从数据库中出来经过编译的 throw new BadCredentialsException("密码不正确"); } //创建一个新的token UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); //在securityContext中添加该验证信息 token = jwtTokenUtil.generateToken(userDetails); //updateLoginTimeByUsername(username); //insertLoginLog(username); } catch (AuthenticationException e) { LOGGER.warn("登录异常:{}", e.getMessage()); } return token; }
Example #4
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 #5
Source File: CustomUserDetailsAuthenticationProvider.java From multitenancy with Apache License 2.0 | 7 votes |
@Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } // Get the password submitted by the end user String presentedPassword = authentication.getCredentials().toString(); // If the password stored in the database and the user submitted password do not // match, then signal a login error if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } }
Example #6
Source File: IntegrationTest.java From codenjoy with GNU General Public License v3.0 | 6 votes |
@Before public void setup() { timer.resume(); debug.setDebugEnable(false); smsProperties.setEnabled(false); verificationCode = "123456"; mvc = MockMvcBuilders.webAppContextSetup(context).build(); SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken( config.getAdminLogin(), config.getAdminPassword() )); }
Example #7
Source File: TokenAuthenticationFilter.java From training with MIT License | 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.getUserIdFromToken(jwt); UserDetails userDetails = customUserDetailsService.loadUserById(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 #8
Source File: MemoryJwtAccessTokenConverter.java From open-capacity-platform with Apache License 2.0 | 6 votes |
public Authentication extractAuthentication(Map<String, ?> map) { if (map.containsKey(USERNAME)) { Object principal = map.get(USERNAME); // Collection<? extends GrantedAuthority> authorities = getAuthorities(map); LoginAppUser loginUser = null; if (principal instanceof Map) { loginUser = BeanUtil.mapToBean((Map) principal, LoginAppUser.class, true); Set<SysRole> roles = new HashSet<>(); for(Iterator<SysRole> it = loginUser.getSysRoles().iterator(); it.hasNext();){ SysRole role = BeanUtil.mapToBean((Map) it.next() , SysRole.class, false); roles.add(role) ; } loginUser.setSysRoles(roles); } return new UsernamePasswordAuthenticationToken(loginUser, "N/A", loginUser.getAuthorities()); } return null; }
Example #9
Source File: StubCartController.java From DataHubSystem with GNU Affero General Public License v3.0 | 6 votes |
@RequestMapping (value = "/users/{userid}/cart/{cartid}/getcount", method = RequestMethod.GET) public int countProductsInCart(Principal principal, @PathVariable (value = "userid") String userid, @PathVariable (value = "cartid") String cartid) throws ProductCartServiceException { User user = (User)((UsernamePasswordAuthenticationToken) principal). getPrincipal(); fr.gael.dhus.service.ProductCartService productCartService = ApplicationContextProvider.getBean( fr.gael.dhus.service.ProductCartService.class); try { return productCartService.countProductsInCart(user.getUUID()); } catch (Exception e) { e.printStackTrace(); throw new ProductCartServiceException(e.getMessage()); } }
Example #10
Source File: JWTAuthenticationFilter.java From datax-web with MIT License | 6 votes |
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { // 从输入流中获取到登录的信息 try { LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class); rememberMe.set(loginUser.getRememberMe()); return authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>()) ); } catch (IOException e) { logger.error("attemptAuthentication error :{}",e); return null; } }
Example #11
Source File: TestCacheSymDS.java From DataHubSystem with GNU Affero General Public License v3.0 | 6 votes |
private void authenticate () { String name = "authenticatedUser"; Set<GrantedAuthority> roles = new HashSet<> (); roles.add (new SimpleGrantedAuthority (Role.DOWNLOAD.getAuthority ())); roles.add (new SimpleGrantedAuthority (Role.SEARCH.getAuthority ())); roles.add ( new SimpleGrantedAuthority (Role.USER_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 ()); }
Example #12
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 #13
Source File: JwtAuthenticationTokenFilter.java From BigDataPlatform with GNU General Public License v3.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 #14
Source File: UmsAdminServiceImpl.java From BigDataPlatform with GNU General Public License v3.0 | 6 votes |
@Override public String login(String username, String password) { String token = null; //密码需要客户端加密后传递 try { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (!passwordEncoder.matches(password, userDetails.getPassword())) { throw new BadCredentialsException("密码不正确"); } UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); token = jwtTokenUtil.generateToken(userDetails); // updateLoginTimeByUsername(username); insertLoginLog(username); } catch (AuthenticationException e) { LOGGER.warn("登录异常:{}", e.getMessage()); } return token; }
Example #15
Source File: DatabaseAuthenticationProvider.java From WebApplication-Project-Skeleton with MIT License | 6 votes |
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { log.info("retrieveUser, for username={}", username); if (StringUtils.isEmpty(username)) { setHideUserNotFoundExceptions(false);//Setting this will cause UsernameNotFoundExceptions to be thrown instead of BadCredentialsException throw new UsernameNotFoundException("Enter your username."); } User user = userService.findUserByUsername(username); String givenPassword = (String) authentication.getCredentials(); if (user == null || !user.getPassword().equals(givenPassword)) { throw new BadCredentialsException("Incorrect username or password."); } return user; }
Example #16
Source File: JwtAuthenticationTokenFilter.java From HIS 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 #17
Source File: JWTFilterTest.java From jhipster-online with Apache License 2.0 | 6 votes |
@Test public void testJWTFilterWrongScheme() 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(JWTFilter.AUTHORIZATION_HEADER, "Basic " + 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()).isNull(); }
Example #18
Source File: UIEERepositoryDirectoryIT.java From pentaho-kettle with Apache License 2.0 | 6 votes |
/** * Logs in with given username. * * @param username * username of user * @param tenantId * tenant to which this user belongs * @tenantAdmin true to add the tenant admin authority to the user's roles */ private void login( final String username, final ITenant tenant, String[] roles ) { StandaloneSession pentahoSession = new StandaloneSession( username ); pentahoSession.setAuthenticated( tenant.getId(), username ); PentahoSessionHolder.setSession( pentahoSession ); pentahoSession.setAttribute( IPentahoSession.TENANT_ID_KEY, tenant.getId() ); final String password = "password"; List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); if ( roles != null ) { for ( String roleName : roles ) { authorities.add( new SimpleGrantedAuthority( roleName ) ); } } UserDetails userDetails = new User( username, password, true, true, true, true, authorities ); Authentication auth = new UsernamePasswordAuthenticationToken( userDetails, password, authorities ); PentahoSessionHolder.setSession( pentahoSession ); // this line necessary for Spring Security's MethodSecurityInterceptor SecurityContextHolder.getContext().setAuthentication( auth ); createUserHomeFolder( tenant, username ); }
Example #19
Source File: JwtAuthenticationTokenFilter.java From mall-tiny 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 #20
Source File: PasswordResetterImplTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Test void testChangePasswordAuthenticatedUser() { String username = "MyUsername"; String password = "MyPassword"; SecurityContext securityContext = mock(SecurityContext.class); Authentication authentication = new UsernamePasswordAuthenticationToken(username, "MyCurrentPassword"); when(securityContext.getAuthentication()).thenReturn(authentication); SecurityContextHolder.setContext(securityContext); User user = mock(User.class); when(userService.getUser(username)).thenReturn(user); passwordResetServiceImpl.changePasswordAuthenticatedUser(password); verify(user).setChangePassword(false); verify(userService).update(user); }
Example #21
Source File: CalendarUserAuthenticationProvider.java From Spring-Security-Third-Edition with MIT License | 6 votes |
@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; }
Example #22
Source File: JWTFilterUnitTest.java From tutorials with MIT License | 6 votes |
@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(JWTFilter.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); }
Example #23
Source File: SpringSecurityUserContext.java From Spring-Security-Third-Edition with MIT License | 5 votes |
/** * Sets the {@link CalendarUser} as the current {@link Authentication}'s principal. It uses */ @Override public void setCurrentUser(CalendarUser user) { if (user == null) { throw new IllegalArgumentException("user cannot be null"); } Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), authorities); SecurityContextHolder.getContext().setAuthentication(authentication); }
Example #24
Source File: SecurityUtilsUnitTest.java From ehcache3-samples with Apache License 2.0 | 5 votes |
@Test public void testIsCurrentUserInRole() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities)); SecurityContextHolder.setContext(securityContext); assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.USER)).isTrue(); assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)).isFalse(); }
Example #25
Source File: SpringSecurityUserContext.java From Spring-Security-Third-Edition with MIT License | 5 votes |
@Override public void setCurrentUser(CalendarUser user) { if (user == null) { throw new IllegalArgumentException("user cannot be null"); } UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); }
Example #26
Source File: ManualMockMvcTests.java From Spring with Apache License 2.0 | 5 votes |
@Test public void contextApplySpringSecurity() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(springSecurity()).build(); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( "user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(authentication); mockMvc.perform(get("/")).andExpect(status().isOk()); mockMvc.perform(get("/")).andExpect(status().isOk()); }
Example #27
Source File: JwtAuthenticationTokenFilter.java From SpringBootLearn with Apache License 2.0 | 5 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authToken = request.getHeader(this.tokenHeader); System.out.println(authToken); if (StringUtils.isNotEmpty(authToken) && authToken.startsWith(authTokenStart)) { authToken = authToken.substring(authTokenStart.length()); log.info("请求" + request.getRequestURI() + "携带的token值:" + authToken); //如果在token过期之前触发接口,我们更新token过期时间,token值不变只更新过期时间 //获取token生成时间 Date createTokenDate = jwtTokenUtil.getCreatedDateFromToken(authToken); log.info("createTokenDate: " + createTokenDate); } else { // 不按规范,不允许通过验证 authToken = null; } String username = jwtTokenUtil.getUsernameFromToken(authToken); log.info("JwtAuthenticationTokenFilter[doFilterInternal] checking authentication " + username); if (jwtTokenUtil.containToken(username, authToken) && username != null && SecurityContextHolder.getContext().getAuthentication() == null) { SecurityUser userDetail = jwtTokenUtil.getUserFromToken(authToken); if (jwtTokenUtil.validateToken(authToken, userDetail)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); log.info(String.format("Authenticated userDetail %s, setting security context", username)); SecurityContextHolder.getContext().setAuthentication(authentication); } } chain.doFilter(request, response); }
Example #28
Source File: SecurityUtilsUnitTest.java From jhipster-microservices-example with Apache License 2.0 | 5 votes |
@Test public void testgetCurrentUserJWT() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token")); SecurityContextHolder.setContext(securityContext); String jwt = SecurityUtils.getCurrentUserJWT(); assertThat(jwt).isEqualTo("token"); }
Example #29
Source File: SpringSecurityUserContext.java From Spring-Security-Third-Edition with MIT License | 5 votes |
@Override public void setCurrentUser(CalendarUser user) { if (user == null) { throw new IllegalArgumentException("user cannot be null"); } UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); }
Example #30
Source File: SpringSecurityUserContext.java From Spring-Security-Third-Edition with MIT License | 5 votes |
@Override public void setCurrentUser(CalendarUser user) { if (user == null) { throw new IllegalArgumentException("user cannot be null"); } UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); }