org.springframework.security.core.context.SecurityContextHolder Java Examples

The following examples show how to use org.springframework.security.core.context.SecurityContextHolder. 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: JWTFilterTest.java    From jhipster-microservices-example with Apache License 2.0 7 votes vote down vote up
@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(JWTConfigurer.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 #2
Source File: JWTFilterTest.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: _CustomSignInAdapter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
    try {
        UserDetails user = userDetailsService.loadUserByUsername(userId);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            user,
            null,
            user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String jwt = tokenProvider.createToken(authenticationToken, false);
        ServletWebRequest servletWebRequest = (ServletWebRequest) request;
        servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
    } catch (AuthenticationException exception) {
        log.error("Social authentication error");
    }
    return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
 
Example #4
Source File: JwtAuthenticationFilter.java    From Spring-Boot-Blog-REST-API with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: JwtTokenFilter.java    From spring-boot-jwt with MIT License 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
  String token = jwtTokenProvider.resolveToken(httpServletRequest);
  try {
    if (token != null && jwtTokenProvider.validateToken(token)) {
      Authentication auth = jwtTokenProvider.getAuthentication(token);
      SecurityContextHolder.getContext().setAuthentication(auth);
    }
  } catch (CustomException ex) {
    //this is very important, since it guarantees the user is not authenticated at all
    SecurityContextHolder.clearContext();
    httpServletResponse.sendError(ex.getHttpStatus().value(), ex.getMessage());
    return;
  }

  filterChain.doFilter(httpServletRequest, httpServletResponse);
}
 
Example #6
Source File: FrontendSmokeTest.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
@Test
public void should_delete_network() throws Exception {
    UserVO user = new UserVO();
    user.setLogin(RandomStringUtils.randomAlphabetic(10));
    user.setRole(UserRole.ADMIN);
    user = userService.createUser(user, VALID_PASSWORD);

    String namePrefix = RandomStringUtils.randomAlphabetic(10);
    NetworkVO network = new NetworkVO();
    network.setName(namePrefix + randomUUID());
    network.setDescription("network description_" + randomUUID());

    NetworkVO created = networkService.create(network);
    assertThat(created.getId(), notNullValue());
    userService.assignNetwork(user.getId(), network.getId());

    final HivePrincipal principal = new HivePrincipal(user);
    SecurityContextHolder.getContext().setAuthentication(new HiveAuthentication(principal));

    boolean deleted = networkService.delete(created.getId(), true);
    assertTrue(deleted);

    created = networkDao.find(created.getId());
    assertThat(created, Matchers.nullValue());
}
 
Example #7
Source File: SpringSecurityCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void checkCurrentToken() {
    final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal =
            checkPrincipalFromCookie();
    if (principal != null) {
        final RefreshableKeycloakSecurityContext securityContext =
                principal.getKeycloakSecurityContext();
        KeycloakSecurityContext current = ((OIDCHttpFacade) facade).getSecurityContext();
        if (current != null) {
            securityContext.setAuthorizationContext(current.getAuthorizationContext());
        }
        final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
        final OidcKeycloakAccount account =
                new SimpleKeycloakAccount(principal, roles, securityContext);
        SecurityContextHolder.getContext()
                .setAuthentication(new KeycloakAuthenticationToken(account, false));
    } else {
        super.checkCurrentToken();
    }
    cookieChecked = true;
}
 
Example #8
Source File: QuestionAction.java    From ExamStack with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 添加试题
 * 
 * @param question
 * @return
 */
@RequestMapping(value = "/secure/question/question-add", method = RequestMethod.POST)
public @ResponseBody Message addQuestion(@RequestBody Question question) {

	UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	Message message = new Message();
	Gson gson = new Gson();
	question.setContent(gson.toJson(question.getQuestionContent()));
	question.setCreate_time(new Date());
	question.setCreator(userDetails.getUsername());
	try {
		questionService.addQuestion(question);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		message.setResult("error");
		message.setMessageInfo(e.getClass().getName());
		e.printStackTrace();
	}

	return message;
}
 
Example #9
Source File: FeedbackControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void initFeedbackAnonymous() throws Exception {
  SecurityContextHolder.getContext()
      .setAuthentication(new TestingAuthenticationToken("anonymous", null));

  List<String> adminEmails = Collections.singletonList("[email protected]");
  when(userService.getSuEmailAddresses()).thenReturn(adminEmails);
  verify(userService, never()).getUser("anonymous");

  mockMvcFeedback
      .perform(get(FeedbackController.URI))
      .andExpect(status().isOk())
      .andExpect(view().name("view-feedback"))
      .andExpect(model().attribute("adminEmails", adminEmails))
      .andExpect(model().attributeDoesNotExist("userName"))
      .andExpect(model().attributeDoesNotExist("userEmail"));
}
 
Example #10
Source File: UserJWTController.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@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<>(exception.getLocalizedMessage(), HttpStatus.UNAUTHORIZED);
    }
}
 
Example #11
Source File: LdapAuthFilter.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Calls an external API to get the user profile using a given access token.
 * @param app the app where the user will be created, use null for root app
 * @param accessToken access token - in the case of LDAP this is should be "uid:password"
 * @return {@link UserAuthentication} object or null if something went wrong
 * @throws IOException ex
 */
public UserAuthentication getOrCreateUser(App app, String accessToken) throws IOException {
	UserAuthentication userAuth = null;
	if (accessToken != null && accessToken.contains(Config.SEPARATOR)) {
		String[] parts = accessToken.split(Config.SEPARATOR, 2);
		String username = parts[0];
		String password = parts[1];
		try {
			Authentication auth = new LDAPAuthentication(username, password).withApp(app);

			// set authentication in context to avoid warning message from SpringSecurityAuthenticationSource
			SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key",
					"anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
			Authentication ldapAuth = getAuthenticationManager().authenticate(auth);
			if (ldapAuth != null) {
				//success!
				userAuth = getOrCreateUser(app, ldapAuth);
			}
		} catch (Exception ex) {
			LOG.info("Failed to authenticate '{}' with LDAP server: {}", username, ex.getMessage());
		}
	}
	return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), false);
}
 
Example #12
Source File: AccessTokenUtils.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
public static Optional<String> getAccessTokenFromSecurityContext() {
    SecurityContext securityContext = SecurityContextHolder.getContext();

    Authentication authentication = securityContext.getAuthentication();
    if (authentication instanceof OAuth2Authentication) {
        Object userDetails = ((OAuth2Authentication) authentication).getUserAuthentication().getDetails();
        if (userDetails != null) {
            try {
                final Map details = (Map) userDetails;
                return Optional.ofNullable(((String) details.get(ACCESS_TOKEN)));
            } catch (ClassCastException e) {

                return Optional.empty();
            }
        } else {

            return Optional.empty();
        }
    }

    return Optional.empty();
}
 
Example #13
Source File: ApplicationResource.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private void validateDeveloperHasAccessToApp(EntityBody app) {
    SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (sandboxEnabled) {
        @SuppressWarnings("unchecked")
        Map<String, Object> metaData = (Map<String, Object>) app.get("metaData");
        if (metaData != null) {
            String tenantId = (String) metaData.get("tenantId");
            if (tenantId != null && tenantId.equals(principal.getTenantId())) {
                return;
            }
        }
        throw new APIAccessDeniedException("Developer " + principal.getExternalId()
                + " does not share the same tenant as the creator of this app and cannot modify it.");
    } else {
        if (!(principal.getExternalId().equals(app.get(CREATED_BY)) || belongToSameSandboxTenant(app, principal.getSandboxTenant()))) {
            throw new APIAccessDeniedException("Developer " + principal.getExternalId()
                    + " is not the creator of this app and does not share same sandbox tenant as the creator hence cannot modify it.");
        }
    }
}
 
Example #14
Source File: AccountsController.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/accounts", method = RequestMethod.GET)
public String accounts(Model model) {
	logger.debug("/accounts");
	model.addAttribute("marketSummary", summaryService.getMarketSummary());
	
	//check if user is logged in!
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (!(authentication instanceof AnonymousAuthenticationToken)) {
	    String currentUserName = authentication.getName();
	    logger.debug("accounts: User logged in: " + currentUserName);
	    
	    try {
	    	model.addAttribute("accounts",accountService.getAccounts(currentUserName));
	    } catch (HttpServerErrorException e) {
	    	logger.debug("error retrieving accounts: " + e.getMessage());
	    	model.addAttribute("accountsRetrievalError",e.getMessage());
	    }
	}
	
	return "accounts";
}
 
Example #15
Source File: UmsAdminServiceImpl.java    From mall-learning with Apache License 2.0 6 votes vote down vote up
@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);
    } catch (AuthenticationException e) {
        LOGGER.warn("登录异常:{}", e.getMessage());
    }
    return token;
}
 
Example #16
Source File: SpringOAuthController.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
/**
 * This method will check if valid user is logged in.
 * @return boolean if user is logged In
 */
@ModelAttribute("validUserLogin")
public boolean isUserLoggedIn() {
	return SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
			 //when Anonymous Authentication is enabled
			 !(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken); 
}
 
Example #17
Source File: DeviceResourceImpl.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
@Override
public void count(String name, String namePattern, Long networkId, String networkName, AsyncResponse asyncResponse) {
    logger.debug("Device count requested");
    HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    deviceService.count(name, namePattern, networkId, networkName, principal)
            .thenApply(count -> {
                logger.debug("Device count request proceed successfully");
                return ResponseFactory.response(OK, count, JsonPolicyDef.Policy.DEVICES_LISTED);
            }).thenAccept(asyncResponse::resume);
}
 
Example #18
Source File: HomeController.java    From Spring with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ModelAndView logOut(SecurityContextHolder sch, HttpServletRequest request) throws ServletException {
	ModelAndView mav = new ModelAndView("home");
	request.logout();
	//sch.getContext().setAuthentication(null);
	//sch.clearContext();
	return mav;
}
 
Example #19
Source File: JwtAuthenticationTokenFilter.java    From tour-of-heros-api-security-zerhusen with MIT License 5 votes vote down vote up
@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);

    if(authToken != null && authToken.startsWith("Bearer ")) {
        authToken = authToken.substring(7);
    }

    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    logger.info("checking authentication für user " + 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);

        // 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);
}
 
Example #20
Source File: NamespaceSecurityAdviceTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void checkPermissionAssertAccessDeniedWhenNoPermissionsNamespaceTrimmed() throws Exception
{
    // Mock a join point of the method call
    // mockMethod(" foo ");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] {BLANK_TEXT + "foo" + BLANK_TEXT});

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    // User has permission to "bar" but the actual namespace given is " foo "
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("bar", Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));

    try
    {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    }
    catch (Exception e)
    {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"foo\"", userId), e.getMessage());
    }
}
 
Example #21
Source File: EchoController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@ResponseBody
@RequestMapping("/echo")
public String echo() throws UnsupportedEncodingException {
    final CasAuthenticationToken token = (CasAuthenticationToken) SecurityContextHolder
            .getContext()
            .getAuthentication();
    // The proxyTicket could be cached in session and reused if we wanted to
    final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);

    // Make a remote call using the proxy ticket
    return restClient.getForObject(targetUrl+"?ticket={pt}", String.class, proxyTicket);
}
 
Example #22
Source File: SecurityUtils.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Check if a user is authenticated.
 *
 * @return true if the user is authenticated, false otherwise
 */
public static boolean isAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> authentication.getAuthorities().stream()
            .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)))
        .orElse(false);
}
 
Example #23
Source File: HomeController.java    From Spring with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value="/logout", method = RequestMethod.GET)
  public ModelAndView logOut(SecurityContextHolder sch,HttpServletRequest request) throws ServletException {
  	ModelAndView mav = new ModelAndView("home");
request.logout();
  	//sch.getContext().setAuthentication(null);
//sch.clearContext();
      return mav;
  }
 
Example #24
Source File: Oauth2AuthenticationManager.java    From ods-provisioning-app with Apache License 2.0 5 votes vote down vote up
/** @see IODSAuthnzAdapter#getUserName() */
public String getUserName() {
  Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  if (DefaultOidcUser.class.isInstance(principal)) {
    return ((DefaultOidcUser) principal).getEmail();
  } else if (CrowdUserDetails.class.isInstance(principal)) {
    return ((CrowdUserDetails) principal).getUsername();
  } else {
    throw new RuntimeException(
        String.format(
            "Unexpected error! Contact developers! Unsupported Principal object class '%s'! Supported Principal classes are String or DefaultOAuth2User",
            principal.getClass()));
  }
}
 
Example #25
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@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: AuthorizationFilter.java    From microservice-integration with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    log.info("Filter过滤器正在执行...");
    // pass the request along the filter chain
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    System.out.println(request.getServletPath());
    String userId = request.getHeader(SecurityConstants.USER_ID_IN_HEADER);

    if (StringUtils.isNotEmpty(userId)) {
        UserContext userContext = new UserContext(UUID.fromString(userId));
        userContext.setAccessType(AccessType.ACCESS_TYPE_NORMAL);

        List<Permission> permissionList = feignAuthClient.getUserPermissions(userId);
        List<SimpleGrantedAuthority> authorityList = new ArrayList();
        for (Permission permission : permissionList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority();
            authority.setAuthority(permission.getPermission());
            authorityList.add(authority);
        }

        CustomAuthentication userAuth = new CustomAuthentication();
        userAuth.setAuthorities(authorityList);
        userContext.setAuthorities(authorityList);
        userContext.setAuthentication(userAuth);
        SecurityContextHolder.setContext(userContext);
    }
    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example #27
Source File: UmsMemberServiceImpl.java    From mall-swarm with Apache License 2.0 5 votes vote down vote up
@Override
public UmsMember getCurrentMember() {
    SecurityContext ctx = SecurityContextHolder.getContext();
    Authentication auth = ctx.getAuthentication();
    MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
    return memberDetails.getUmsMember();
}
 
Example #28
Source File: NamespaceSecurityHelper.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the ApplicationUser in the current security context. Assumes the user is already authenticated, and the authenticated user is constructed through
 * the application's authentication mechanism.
 *
 * @return The ApplicationUser or null if not authenticated
 */
private ApplicationUser getApplicationUser()
{
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal != null && principal instanceof SecurityUserWrapper)
    {
        SecurityUserWrapper securityUserWrapper = (SecurityUserWrapper) principal;
        return securityUserWrapper.getApplicationUser();
    }
    return null;
}
 
Example #29
Source File: RestController.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@PostMapping("/logout")
@ResponseStatus(OK)
public void logout(@TokenParam(required = true) String token, HttpServletRequest request) {
  tokenService.removeToken(token);
  SecurityContextHolder.getContext().setAuthentication(null);

  if (request.getSession(false) != null) {
    request.getSession().invalidate();
  }
}
 
Example #30
Source File: UserJWTController.java    From tutorials with MIT License 5 votes vote down vote up
@PostMapping("/authenticate")
public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) {

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());

    Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
    String jwt = tokenProvider.createToken(authentication, rememberMe);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
    return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
}