public Authentication getAuthentication(HttpServletRequest request) { String token = request.getHeader(HEADER_STRING); if (token != null) { // parse the token. String user = getUsername(token); String roles = getBody(token).get("roles", String.class); List<GrantedAuthority> grantedAuths = AuthorityUtils.commaSeparatedStringToAuthorityList(roles); return user != null ? new UsernamePasswordAuthenticationToken(user, null, grantedAuths) : null; } return null; }
@SuppressWarnings("PMD.SignatureDeclareThrowsException") private RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() throws Exception { RequestHeaderAuthenticationFilter f = new RequestHeaderAuthenticationFilter(); f.setPrincipalRequestHeader("X-Forwarded-User"); f.setCredentialsRequestHeader("X-Forwarded-Access-Token"); f.setAuthenticationManager(authenticationManager()); f.setAuthenticationDetailsSource( (AuthenticationDetailsSource<HttpServletRequest, PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails>) (request) ->new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( request, AuthorityUtils.createAuthorityList("ROLE_AUTHENTICATED") ) ); f.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler()); f.setExceptionIfHeaderMissing(false); return f; }
@Bean @ConfigurationProperties(prefix = "security.oauth2.client") public BaseClientDetails oauth2ClientDetails() { BaseClientDetails details = new BaseClientDetails(); if (this.client.getClientId() == null) { this.client.setClientId(UUID.randomUUID().toString()); } details.setClientId(this.client.getClientId()); details.setClientSecret(this.client.getClientSecret()); details.setAuthorizedGrantTypes(Arrays.asList("authorization_code", "password", "client_credentials", "implicit", "refresh_token")); details.setAuthorities( AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); details.setRegisteredRedirectUri(Collections.<String>emptySet()); return details; }
@Test public void testAuthorizationServerOverride() { this.context = new AnnotationConfigServletWebServerApplicationContext(); TestPropertyValues.of("security.oauth2.resourceId:resource-id") .applyTo(this.context); this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomAuthorizationServer.class, MinimalSecureWebApplication.class); this.context.refresh(); BaseClientDetails config = new BaseClientDetails(); config.setClientId("client"); config.setClientSecret("secret"); config.setResourceIds(Arrays.asList("resource-id")); config.setAuthorizedGrantTypes(Arrays.asList("password")); config.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("USER")); config.setScope(Arrays.asList("read")); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); verifyAuthentication(config); }
public static Authentication getAuthentication(HttpServletRequest request) { // 从Header中拿到token String token = request.getHeader(HEADER_STRING); if (token == null) { token = getTokenFromCookis(request); } if (token != null && !token.isEmpty()) { // 解析 Token Claims claims = Jwts.parser().setSigningKey(SECRET) .parseClaimsJws(token).getBody(); // 获取用户名 String user = claims.get("UserId").toString(); // 获取权限(角色) List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities")); // 返回验证令牌 return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null; } return null; }
@Bean @Override public UserDetailsService userDetailsService() { return username -> { UserAccount account = userAccountService.findByUsername(username); if(account != null) { RequestContext.getInstance().set(account); return new User(account.getUserName(), account.getPassword(), account.getEnabled(), account.getAccountNonExpired(), true, account.getAccountNonLocked(), AuthorityUtils.createAuthorityList(account.getAuthorities())); } else { throw new UsernameNotFoundException("could not find the user '" + username + "'"); } }; }
/** * Configures the Spring Security {@link SecurityContext} to be authenticated as the user with the given username and * password as well as the given granted authorities. * * @param username must not be {@literal null} or empty. * @param password must not be {@literal null} or empty. * @param roles */ public static void runAs(String username, String password, String... roles) { Assert.notNull(username, "Username must not be null!"); Assert.notNull(password, "Password must not be null!"); SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken(username, password, AuthorityUtils.createAuthorityList(roles))); }
@Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { // 通过用户名获取用户信息 Account account = accountRepository.findByName(name); if (account != null) { // 创建spring security安全用户 User user = new User(account.getName(), account.getPassword(), AuthorityUtils.createAuthorityList(account.getRoles())); return user; } else { throw new UsernameNotFoundException("用户[" + name + "]不存在"); } } }; }
/** * Mock OAuth2Request * * @param withMockOAuth2Token * @return */ private OAuth2Request getOauth2Request(WithMockOAuth2Token withMockOAuth2Token) { String clientId = withMockOAuth2Token.clientId(); Map<String, String> requestParameters = Collections.emptyMap(); boolean approved = true; String redirectUrl = withMockOAuth2Token.redirectUrl(); Set<String> responseTypes = Collections.emptySet(); Set<String> scopes = new HashSet<>(Arrays.asList(withMockOAuth2Token.scopes())); Set<String> resourceIds = Collections.emptySet(); Map<String, Serializable> extensionProperties = Collections.emptyMap(); List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities()); OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities, approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties); return oAuth2Request; }
@Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { User user = dao.getUserByEmail(email); if(user != null) { return new org.springframework.security.core.userdetails.User( user.getEmail(), user.getPassword(), user.valid(), true, true, true, AuthorityUtils.createAuthorityList(user.fetchAuthorities()) ); } else { throw new UsernameNotFoundException("Could not find that user"); } } }; }
@Before public void setup() { if (this.registry != null) { this.registry.clear(); } this.context = SecurityContextHolder.createEmptyContext(); this.context.setAuthentication( new UsernamePasswordAuthenticationToken("username-" + UUID.randomUUID(), "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); this.changedContext = SecurityContextHolder.createEmptyContext(); this.changedContext.setAuthentication(new UsernamePasswordAuthenticationToken( "changedContext-" + UUID.randomUUID(), "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); }
public ClientDetails build() { BaseClientDetails result = new BaseClientDetails(); result.setClientId(clientId); result.setAuthorizedGrantTypes(authorizedGrantTypes); result.setAccessTokenValiditySeconds(accessTokenValiditySeconds); result.setRefreshTokenValiditySeconds(refreshTokenValiditySeconds); result.setRegisteredRedirectUri(registeredRedirectUris); result.setClientSecret(secret); result.setScope(scopes); result.setAuthorities(AuthorityUtils.createAuthorityList(authorities.toArray(new String[authorities.size()]))); result.setResourceIds(resourceIds); result.setAdditionalInformation(additionalInformation); if (autoApprove) { result.setAutoApproveScopes(scopes); } else { result.setAutoApproveScopes(autoApproveScopes); } return result; }
@Bean UserDetailsService userDetailsService() { return username -> { LOGGER.debug(String.format("Looking for user [%s]", username)); Account account = accountRepository.findByUsername(username); if (account != null) { LOGGER.info(String.format("Found user [%s]", username)); return new User(account.getUsername(), account.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER")); } else { LOGGER.info(String.format("Couldn't find user [%s]", username)); throw new UsernameNotFoundException(String.format("couldn't find the user '%s'", username)); } }; }
public JWTUserDetails getUserFromToken(String token){ JWTUserDetails user; try { final Claims claims=getClaimsFromToken(token); String userId = getUserIdFromToken(token); String username=claims.getSubject(); List<GrantedAuthority> authorities =AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get(CLAIM_KEY_AUTHORITIES)); /* boolean account_enabled = (Boolean) claims.get(CLAIM_KEY_ACCOUNT_ENABLED); boolean account_non_locked = (Boolean) claims.get(CLAIM_KEY_ACCOUNT_NON_LOCKED); boolean account_non_expired = (Boolean) claims.get(CLAIM_KEY_ACCOUNT_NON_EXPIRED);*/ user = new JWTUserDetails(userId, username, "password", authorities); }catch (Exception e){ logger.error("getUserFromToken error"); user=null; } return user; }
@CacheControl(policy = CachePolicy.NO_CACHE) @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> importMooseDataCard( @RequestParam final MultipartFile xmlFile, @RequestParam final MultipartFile pdfFile) { LOG.debug("Moose data card upload request received via anonymous API"); final SecurityContext sc = SecurityContextHolder.getContext(); sc.setAuthentication(new AnonymousAuthenticationToken( "key", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); if (LOG.isDebugEnabled()) { LOG.debug("Populated SecurityContextHolder with anonymous token: '" + sc.getAuthentication() + "'"); } try { return ResponseEntity.ok(toMap(importFeature.importMooseDataCardWithSpecialPrivilege(xmlFile, pdfFile))); } catch (final MooseDataCardImportException e) { return ResponseEntity.badRequest().body(toMap(e.getMessages())); } }
private static OneTimePasswordAuthenticationProvider createProvider(boolean loginOtp, boolean extAuthOtp) { SecurityConfigurationProperties properties = createMockProperties(loginOtp, extAuthOtp); UserDetailsService userDetailsService = Mockito.mock(UserDetailsService.class); Mockito.when(userDetailsService.loadUserByUsername(ArgumentMatchers.eq(USER))).thenReturn( new User(USER, USER, AuthorityUtils.createAuthorityList("ROLE_USER"))); Mockito.when(userDetailsService.loadUserByUsername(ArgumentMatchers.eq(ADMIN))).thenReturn( new User(ADMIN, ADMIN, AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); Mockito.when(userDetailsService.loadUserByUsername(ArgumentMatchers.eq(MODERATOR))).thenReturn( new User(MODERATOR, MODERATOR, AuthorityUtils.createAuthorityList("ROLE_MODERATOR"))); OneTimePasswordAuthenticationProvider provider = new OneTimePasswordAuthenticationProvider(); provider.setSecurityConfigurationProperties(properties); provider.setUserDetailsService(userDetailsService); provider.setPasswordEncoder(new PlaintextPasswordEncoder()); OneTimePasswordCodeService codeService = new OneTimePasswordCodeService(properties); ReflectionTestUtils.setField(provider, "oneTimePasswordCodeService", codeService); return provider; }
@Bean public UserDetailsService userDetailsService() { return username -> { Optional<Account> accountOptional = accountRepository.findByUsername(username); if (!accountOptional.isPresent()) { throw new UsernameNotFoundException("Could not find the user '" + username + "'"); } Account account = accountOptional.get(); return new User(account.getUsername(), account.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER")); }; }
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { try { Authentication userAuth = null; User user = extensionGrantProvider.grant(convert(tokenRequest)); if (user != null) { userAuth = new UsernamePasswordAuthenticationToken(user, "", AuthorityUtils.NO_AUTHORITIES); if (extensionGrant.isCreateUser()) { Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters()); parameters.put(RepositoryProviderUtils.SOURCE, extensionGrant.getIdentityProvider()); ((AbstractAuthenticationToken) userAuth).setDetails(parameters); eventPublisher.publishAuthenticationSuccess(userAuth); } } OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); return new OAuth2Authentication(storedOAuth2Request, userAuth); } catch (InvalidGrantException e) { throw new org.springframework.security.oauth2.common.exceptions.InvalidGrantException(e.getMessage(), e); } }
/** * Creates the user authority list from the values of the {@code memberOf} attribute * obtained from the user's Active Directory entry. */ @Override protected Collection<? extends GrantedAuthority> loadUserAuthorities( DirContextOperations userData, String username, String password) { String[] groups = userData.getStringAttributes("memberOf"); if (groups == null) { logger.debug("No values for 'memberOf' attribute."); return AuthorityUtils.NO_AUTHORITIES; } if (logger.isDebugEnabled()) { logger.debug("'memberOf' attribute values: " + Arrays.asList(groups)); } ArrayList<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>( groups.length); for (String group : groups) { authorities.add(new SimpleGrantedAuthority(new DistinguishedName(group).removeLast().getValue())); } return authorities; }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Authentication auth = AuthenticatedRequest .getSpinnakerUser() .map(username -> (Authentication) new PreAuthenticatedAuthenticationToken(username, null, new ArrayList<>())) .orElseGet(() -> new AnonymousAuthenticationToken( "anonymous", "anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS") )); val ctx = SecurityContextHolder.createEmptyContext(); ctx.setAuthentication(auth); SecurityContextHolder.setContext(ctx); log.debug("Set SecurityContext to user: {}", auth.getPrincipal().toString()); chain.doFilter(request, response); }
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // TODO Auto-generated method stub User user = userMapper.getUserByName(username); if(user == null) throw new UsernameNotFoundException("user not found!"); //roles=角色代码 List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()); userInfo = new UserInfo(username,"",user.isEnabled(),true,true,true,authorities); userInfo.setUserid(user.getUserId()); userInfo.setRolesName(user.getRoles()); userInfo.setTrueName(user.getTrueName()); userInfo.setEmail(user.getEmail()); userInfo.setPhoneNum(user.getPhoneNum()); userInfo.setNationalId(user.getNationalId()); userInfo.setDepId(user.getDepId()); return userInfo; }
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // TODO Auto-generated method stub User user = null; try { user = userMapper.getUserByName(username); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(user == null) throw new UsernameNotFoundException("user not found!"); //roles=角色代码 List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()); userInfo = new UserInfo(username,user.getPassword(),user.isEnabled(),true,true,true,authorities); userInfo.setUserid(user.getUserId()); userInfo.setRolesName(user.getRoles()); userInfo.setTrueName(user.getTrueName()); userInfo.setEmail(user.getEmail()); userInfo.setPhoneNum(user.getPhoneNum()); userInfo.setNationalId(user.getNationalId()); userInfo.setDepId(user.getDepId()); return userInfo; }
@Bean @ConfigurationProperties("security.oauth2.client") public BaseClientDetails oauth2ClientDetails() { BaseClientDetails details = new BaseClientDetails(); if (this.client.getClientId() == null) { this.client.setClientId(UUID.randomUUID().toString()); } details.setClientId(this.client.getClientId()); details.setClientSecret(this.client.getClientSecret()); details.setAuthorizedGrantTypes(Arrays.asList("authorization_code", "password", "client_credentials", "implicit", "refresh_token")); details.setAuthorities( AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); details.setRegisteredRedirectUri(Collections.<String>emptySet()); return details; }
@Test public void testOverrideAuthenticationManagerWithBuilderAndInjectIntoSecurityFilter() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(AuthenticationManagerCustomizer.class, SecurityCustomizer.class, SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken( "foo", "bar", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user)) .isNotNull(); pingAuthenticationListener(); }
@Test public void testOverrideAuthenticationManagerWithBuilderAndInjectBuilderIntoSecurityFilter() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(AuthenticationManagerCustomizer.class, WorkaroundSecurityCustomizer.class, SecurityAutoConfiguration.class, ServerPropertiesAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken( "foo", "bar", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")); assertThat(this.context.getBean(AuthenticationManager.class).authenticate(user)) .isNotNull(); }
@Test public void testAuthorizationServerOverride() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "security.oauth2.resourceId:resource-id"); this.context.register(AuthorizationAndResourceServerConfiguration.class, CustomAuthorizationServer.class, MinimalSecureWebApplication.class); this.context.refresh(); BaseClientDetails config = new BaseClientDetails(); config.setClientId("client"); config.setClientSecret("secret"); config.setResourceIds(Arrays.asList("resource-id")); config.setAuthorizedGrantTypes(Arrays.asList("password")); config.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("USER")); config.setScope(Arrays.asList("read")); assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0); assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(1); verifyAuthentication(config); }
private List<SecurityQuestionDefinitionType> getQuestions(PrismObject<UserType> user) { return getSecurityEnforcer().runPrivileged(new Producer<List<SecurityQuestionDefinitionType>>() { @Override public List<SecurityQuestionDefinitionType> run() { Task task = getTaskManager().createTaskInstance("Search user by name"); OperationResult result = task.getResult(); SecurityPolicyType securityPolicyType = null; try { SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("rest_sec_q_auth", "REST", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); securityPolicyType = modelInteractionService.getSecurityPolicy(user, task, result); } catch (ObjectNotFoundException | SchemaException e) { return null; } finally { SecurityContextHolder.getContext().setAuthentication(null); } if (securityPolicyType.getCredentials() != null && securityPolicyType.getCredentials().getSecurityQuestions() != null){ return securityPolicyType.getCredentials().getSecurityQuestions().getQuestion(); } return null; } }); }
@Override protected UserDetailsService userDetailsService() { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Account account = accountRepository.findByLogin(username); if(account != null) { return new User(account.getLogin(), account.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER")); } else { throw new UsernameNotFoundException("could not find the user '" + username + "'"); } } }; }
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { String targetUrl = "/"; Set<String> authorities = AuthorityUtils.authorityListToSet(authentication.getAuthorities()); if (authorities.contains("ROLE_OWNER")) { targetUrl = "/owner"; } else if (authorities.contains("ROLE_CLIENT")) { targetUrl = "/client"; } else if (authorities.contains("ROLE_RECEPTION")) { targetUrl = "/reception"; } else { throw new IllegalStateException("Niedozwolona rola użytkownika!"); } if (response.isCommitted()) return; redirectStrategy.sendRedirect(request, response, targetUrl); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (globalConfig.getRestAnonymousEnabled()) { if (SecurityContextHolder.getContext().getAuthentication() == null) { UUID anonymousSessionId = globalConfig.getAnonymousSessionId(); CubaAnonymousAuthenticationToken anonymousAuthenticationToken = new CubaAnonymousAuthenticationToken("anonymous", AuthorityUtils.createAuthorityList("ROLE_CUBA_ANONYMOUS")); SecurityContextHolder.getContext().setAuthentication(anonymousAuthenticationToken); AppContext.setSecurityContext(new SecurityContext(anonymousSessionId)); } else { log.debug("SecurityContextHolder not populated with cuba anonymous token, as it already contained: '{}'", SecurityContextHolder.getContext().getAuthentication()); } } else { log.trace("Anonymous access for CUBA REST API is disabled"); } chain.doFilter(request, response); }
@Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String username) { logger.info("Got https client name of " + username); if (username.equals("cid") || username.equals("learnsphere")) { return new User(username, "", AuthorityUtils .commaSeparatedStringToAuthorityList("TRUSTED_USER_AGENT")); } else { return null; } } }; }
@Bean UserDetailsService userDetailsService() { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { Account account = (Account) accountRepository .findByEmailAddress(email); if (account != null) { return new WebUser(account.getEmailAddress(), account.getCryptedPassword(), account.getActive(), true, true, true, AuthorityUtils.createAuthorityList("USER"), account); } else { throw new UsernameNotFoundException( "could not find the user '" + email + "'"); } } }; }
@Override public AuthenticatedExternalWebService authenticate(String username, String password) { ExternalWebServiceStub externalWebService = new ExternalWebServiceStub(); // Do all authentication mechanisms required by external web service protocol and validated response. // Throw descendant of Spring AuthenticationException in case of unsucessful authentication. For example BadCredentialsException User user = userSecurityService.getUser(username); if(user == null || !password.equals(user.getPassword())) { throw new BadCredentialsException("user " + username + " not found"); } // If authentication to external service succeeded then create authenticated wrapper with proper Principal and GrantedAuthorities. // GrantedAuthorities may come from external service authentication or be hardcoded at our layer as they are here with ROLE_DOMAIN_USER AuthenticatedExternalWebService authenticatedExternalWebService = new AuthenticatedExternalWebService( YopeUser.builder().username(username).password(password).build(), null, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_DOMAIN_USER")); authenticatedExternalWebService.setExternalWebService(externalWebService); return authenticatedExternalWebService; }