org.springframework.security.core.GrantedAuthority Java Examples
The following examples show how to use
org.springframework.security.core.GrantedAuthority.
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: TokenProvider.java From e-commerce-microservice with Apache License 2.0 | 7 votes |
public String createToken(Authentication authentication, boolean rememberMe) { String authorities = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity; if (rememberMe) { validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); } else { validity = new Date(now + this.tokenValidityInMilliseconds); } return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .signWith(key, SignatureAlgorithm.HS512) .setExpiration(validity) .compact(); }
Example #2
Source File: SecurityConfiguration.java From java-microservices-examples with Apache License 2.0 | 7 votes |
/** * Map authorities from "groups" or "roles" claim in ID Token. * * @return a {@link GrantedAuthoritiesMapper} that maps groups from * the IdP to Spring Security Authorities. */ @Bean @SuppressWarnings("unchecked") public GrantedAuthoritiesMapper userAuthoritiesMapper() { return (authorities) -> { Set<GrantedAuthority> mappedAuthorities = new HashSet<>(); authorities.forEach(authority -> { OidcUserAuthority oidcUserAuthority = (OidcUserAuthority) authority; OidcUserInfo userInfo = oidcUserAuthority.getUserInfo(); Collection<String> groups = (Collection<String>) userInfo.getClaims().get("groups"); if (groups == null) { groups = (Collection<String>) userInfo.getClaims().get("roles"); } mappedAuthorities.addAll(groups.stream() .filter(group -> group.startsWith("ROLE_")) .map(SimpleGrantedAuthority::new).collect(Collectors.toList())); }); return mappedAuthorities; }; }
Example #3
Source File: CustomUserDetailsService.java From spring-security with Apache License 2.0 | 6 votes |
/** * 认证过程中 - 根据登录信息获取用户详细信息 * * @param s 登录用户输入的用户名 * @return * @throws UsernameNotFoundException */ @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { //根据用户输入的用户信息,查询数据库中已注册用户信息 TUser user = userService.findByName(s); //如果用户不存在直接抛出UsernameNotFoundException异常 if (user == null) throw new UsernameNotFoundException("用户名为" + s + "的用户不存在"); List<TRole> roles = user.getRoleList(); List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (TRole role:roles){ List<TPermission> permissions = role.getPermissions(); for (TPermission permission:permissions){ GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getUrl()); // 此处将权限信息添加到 GrantedAuthority 对象中,在后面进行权限验证时会使用GrantedAuthority 对象 grantedAuthorities.add(grantedAuthority); } } return new CustomUserDetails(user, grantedAuthorities); }
Example #4
Source File: AdminServiceRestImpl.java From jwala with Apache License 2.0 | 6 votes |
@Override public Response getAuthorizationDetails() { return ResponseBuilder.ok(new ResponseContent() { private static final String TRUE = "true"; private final String authEnabled = ApplicationProperties.get(JWALA_AUTHORIZATION, TRUE); public String getAuthorizationEnabled() { return authEnabled; } @SuppressWarnings("unchecked") public Collection<GrantedAuthority> getUserAuthorities() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (authEnabled.equalsIgnoreCase(TRUE) && auth != null) { return (Collection<GrantedAuthority>) auth.getAuthorities(); } return null; } }); }
Example #5
Source File: TokenProvider.java From tutorials with MIT License | 6 votes |
public String createToken(Authentication authentication, Boolean rememberMe) { String authorities = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity; if (rememberMe) { validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); } else { validity = new Date(now + this.tokenValidityInMilliseconds); } return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .signWith(SignatureAlgorithm.HS512, secretKey) .setExpiration(validity) .compact(); }
Example #6
Source File: TokenProvider.java From tutorials with MIT License | 6 votes |
public String createToken(Authentication authentication, Boolean rememberMe) { String authorities = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity; if (rememberMe) { validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); } else { validity = new Date(now + this.tokenValidityInMilliseconds); } return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .signWith(SignatureAlgorithm.HS512, secretKey) .setExpiration(validity) .compact(); }
Example #7
Source File: DefaultCategoryPermissionEvaluatorTest.java From attic-rave with Apache License 2.0 | 6 votes |
@Before public void setUp() { mockCategoryRepository = createMock(CategoryRepository.class); defaultCategoryPermissionEvaluator = new DefaultCategoryPermissionEvaluator(mockCategoryRepository); mockAuthentication = createMock(Authentication.class); user = new UserImpl(); user.setUsername(VALID_USERNAME); user.setId(VALID_USER_ID); user2 = new UserImpl(); user2.setUsername(VALID_USERNAME2); category = new CategoryImpl(); category.setId(VALID_WIDGET_CATEGORY_ID); category.setCreatedUserId(VALID_USER_ID); grantedAuthorities = new ArrayList<GrantedAuthority>(); grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER")); }
Example #8
Source File: WebSocketAuthenticatorService.java From joal with Apache License 2.0 | 6 votes |
@SuppressWarnings("TypeMayBeWeakened") public UsernamePasswordAuthenticationToken getAuthenticatedOrFail(final CharSequence username, final CharSequence authToken) throws AuthenticationException { if (StringUtils.isBlank(username)) { throw new AuthenticationCredentialsNotFoundException("Username was null or empty."); } if (StringUtils.isBlank(authToken)) { throw new AuthenticationCredentialsNotFoundException("Authentication token was null or empty."); } if (!appSecretToken.contentEquals(authToken)) { throw new BadCredentialsException("Authentication token does not match the expected token"); } // Everything is fine, return an authenticated Authentication. (the constructor with grantedAuthorities auto set authenticated = true) // null credentials, we do not pass the password along to prevent security flaw return new UsernamePasswordAuthenticationToken( username, null, Collections.singleton((GrantedAuthority) () -> "USER") ); }
Example #9
Source File: PermissionService.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
/** * Checks if at least on permission of the given {@code permissions} * contains in the . In case no {@code context} is available {@code false} * will be returned. * * @param permissions * the permissions to check against the * @return {@code true} if a is available and contains the given * {@code permission}, otherwise {@code false}. * @see SpPermission */ public boolean hasAtLeastOnePermission(final List<String> permissions) { final SecurityContext context = SecurityContextHolder.getContext(); if (context == null) { return false; } final Authentication authentication = context.getAuthentication(); if (authentication == null) { return false; } for (final GrantedAuthority authority : authentication.getAuthorities()) { for (final String permission : permissions) { if (authority.getAuthority().equals(permission)) { return true; } } } return false; }
Example #10
Source File: CustomAuthenticationProvider.java From pivotal-bank-demo with Apache License 2.0 | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); AuthenticationRequest request = new AuthenticationRequest(); request.setUsername(name); request.setPassword(password); try { Map<String, Object> params = service.login(request); if (params != null) { List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority("USER")); Authentication auth = new UsernamePasswordAuthenticationToken( name, password, grantedAuths); return auth; } else { throw new BadCredentialsException("Username not found"); } } catch (HttpServerErrorException e) { throw new BadCredentialsException("Login failed!"); } }
Example #11
Source File: AutenticazioneUtenzeAnonimeDAO.java From govpay with GNU General Public License v3.0 | 6 votes |
public UserDetails loadUserDetails(String username, Collection<? extends GrantedAuthority> authFromPreauth) throws UsernameNotFoundException { BasicBD bd = null; try { String transactionId = UUID.randomUUID().toString(); this.debug(transactionId, "Caricamento informazioni dell'utenza ["+username+"] in corso..."); bd = BasicBD.newInstance(transactionId, this.useCacheData); GovpayLdapUserDetails userDetailFromUtenzaAnonima = AutorizzazioneUtils.getUserDetailFromUtenzaAnonima(username, this.isCheckPassword(), this.isCheckSubject(), authFromPreauth, bd); userDetailFromUtenzaAnonima.setIdTransazioneAutenticazione(transactionId); this.debug(transactionId, "Caricamento informazioni dell'utenza ["+username+"] completato."); return userDetailFromUtenzaAnonima; } catch(Exception e){ throw new RuntimeException("Errore interno, impossibile caricare le informazioni dell'utenza", e); } finally { if(bd != null) bd.closeConnection(); } }
Example #12
Source File: TokenProvider.java From alchemy with Apache License 2.0 | 6 votes |
public String createToken(Authentication authentication, boolean rememberMe) { String authorities = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity; if (rememberMe) { validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); } else { validity = new Date(now + this.tokenValidityInMilliseconds); } return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .signWith(key, SignatureAlgorithm.HS512) .setExpiration(validity) .compact(); }
Example #13
Source File: CmdbUserDetailService.java From we-cmdb with Apache License 2.0 | 6 votes |
@Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { List<AdmMenu> admMenus = admMenusRepository.findMenusByUserName(username); String password = getPassword(username); if (CollectionUtils.isNotEmpty(admMenus)) { List<GrantedAuthority> authorities = admMenus.stream() .map(AdmMenu::getName) .map(menuName -> new SimpleGrantedAuthority(ROLE_PREFIX + menuName)) .collect(toList()); logger.info("Menu permissions {} found for user {}", authorities, username); return new User(username, password, authorities); } else { logger.warn("No accessible menu found for user {}", username); return new User(username, password, emptyList()); } }
Example #14
Source File: StaffServiceBean.java From bbs with GNU Affero General Public License v3.0 | 6 votes |
/** * 得到用户权限 *@param userAccount 用户账号 *@return */ @Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED) public List<GrantedAuthority> loadUserAuthoritiesByName(String userAccount){ try { List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); List<String> authorities = loadUserAuthorities(userAccount); if(authorities != null && authorities.size() >0){ for (String roleName : authorities) { auths.add(new SimpleGrantedAuthority(roleName)); } } return auths; } catch (RuntimeException re) { if (logger.isErrorEnabled()) { logger.error("得到用户权限",re); } throw re; } }
Example #15
Source File: UserDetailsServiceImpl.java From Spring-Security-Third-Edition with MIT License | 6 votes |
@Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { CalendarUser user = userRepository.findByEmail(username); if (user == null) throw new UsernameNotFoundException("username " + username + " not found"); Set<GrantedAuthority> grantedAuthorities = new HashSet<>(); for (Role role : user.getRoles()){ grantedAuthorities.add(new SimpleGrantedAuthority(role.getName())); } return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities); }
Example #16
Source File: FooAuthenticationProvider.java From spring-auth-example with MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { logger.debug( "==== Authenticating using FooAuthenticationProvider: " + authentication); // here goes username/password authentication for Foo Response response = userService .authenticateFoo(String.valueOf(authentication.getPrincipal()), String.valueOf(authentication.getCredentials())); if (response.isOk()) { List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("FOO_READ")); authorities.add(new SimpleGrantedAuthority("FOO_WRITE")); return new FooUsernamePasswordAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), authorities); } else { throw new BadCredentialsException("Authentication failed."); } }
Example #17
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 #18
Source File: AnonymousAuthenticationFilter.java From govpay with GNU General Public License v3.0 | 6 votes |
public static List<GrantedAuthority> getAuthoritiesUtenzaAnonima() { List<GrantedAuthority> authFromPreauth = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"); UserDetails utenzaAnonima = null; try { AutenticazioneUtenzeAnonimeDAO autenticazioneUtenzeAnonimeDAO = new AutenticazioneUtenzeAnonimeDAO(); autenticazioneUtenzeAnonimeDAO.setApiName("API_PAGAMENTO"); autenticazioneUtenzeAnonimeDAO.setAuthType("PUBLIC"); utenzaAnonima = autenticazioneUtenzeAnonimeDAO.loadUserDetails("anonymousUser", authFromPreauth); } catch (UsernameNotFoundException e) { } if(utenzaAnonima != null) { List<GrantedAuthority> authorities = new ArrayList<>(); authorities.addAll(utenzaAnonima.getAuthorities()); return authorities; } return AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"); }
Example #19
Source File: AutorizzazioneUtils.java From govpay with GNU General Public License v3.0 | 6 votes |
public static GovpayLdapUserDetails getUserDetail(String username, String password, String identificativo, List<GrantedAuthority> authorities) { GovpayLdapUserDetails details = new GovpayLdapUserDetails(); LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence(); essence.setAccountNonExpired(true); essence.setAccountNonLocked(true); essence.setCredentialsNonExpired(true); essence.setEnabled(true); essence.setUsername(username); essence.setPassword(password); essence.setAuthorities(authorities); essence.setDn(identificativo); details.setLdapUserDetailsImpl(essence.createUserDetails()); return details; }
Example #20
Source File: RemoteIdmAuthenticationProvider.java From flowable-engine with Apache License 2.0 | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { RemoteUser user = remoteIdmService.authenticateUser(authentication.getPrincipal().toString(), authentication.getCredentials().toString()); if (user == null) { throw new FlowableException("user not found " + authentication.getPrincipal()); } Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String privilege : user.getPrivileges()) { grantedAuthorities.add(new SimpleGrantedAuthority(privilege)); } Authentication auth = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities); return auth; }
Example #21
Source File: RiskControllerTest.java From OpenLRW with Educational Community License v2.0 | 5 votes |
@Before public void init() throws OrgNotFoundException, LineItemNotFoundException { MockitoAnnotations.initMocks(this); riskController = new RiskController(null, riskService); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_TENANT_ADMIN")); UserContext context = UserContext.create(TestData.TENANT_1, "01", authorities); when(jwtToken.getPrincipal()).thenReturn(context); riskController.post(jwtToken, risk, true); }
Example #22
Source File: SecurityUtilsUnitTest.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 5 votes |
@Test public void testAnonymousIsNotAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isFalse(); }
Example #23
Source File: DefaultCategoryPermissionEvaluatorTest.java From attic-rave with Apache License 2.0 | 5 votes |
@Test public void testHasPermission_3args_administer_hasAdminRole() { grantedAuthorities.add(new SimpleGrantedAuthority(AuthenticationUtils.ROLE_ADMIN)); EasyMock.<Collection<? extends GrantedAuthority>>expect(mockAuthentication.getAuthorities()).andReturn(grantedAuthorities); replay(mockAuthentication); assertThat(defaultCategoryPermissionEvaluator.hasPermission(mockAuthentication, category, ModelPermissionEvaluator.Permission.ADMINISTER), is(true)); verify(mockAuthentication); }
Example #24
Source File: DefaultRegionPermissionEvaluatorTest.java From attic-rave with Apache License 2.0 | 5 votes |
@Test public void testHasPermission_3args_administer_hasAdminRole() { grantedAuthoritiesList.add(new SimpleGrantedAuthority(AuthenticationUtils.ROLE_ADMIN)); EasyMock.<Collection<? extends GrantedAuthority>>expect(mockAuthentication.getAuthorities()).andReturn(grantedAuthoritiesList); replay(mockAuthentication); assertThat(defaultRegionPermissionEvaluator.hasPermission(mockAuthentication, region, ModelPermissionEvaluator.Permission.ADMINISTER), is(true)); verify(mockAuthentication); }
Example #25
Source File: DomainUserDetailsService.java From Spring-5.0-Projects with MIT License | 5 votes |
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { if (!user.getActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream() .map(authority -> new SimpleGrantedAuthority(authority.getName())) .collect(Collectors.toList()); return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities); }
Example #26
Source File: AppUserDetails.java From demo-spring-security-cas with Apache License 2.0 | 5 votes |
@Override public Collection<? extends GrantedAuthority> getAuthorities() { /* * List<GrantedAuthority> l = new ArrayList<GrantedAuthority>(); l.add(new * GrantedAuthority() { private static final long serialVersionUID = 1L; * * @Override public String getAuthority() { return "ROLE_AUTHENTICATED"; } }); return l; */ return authorities; }
Example #27
Source File: ClassControllerTest.java From OpenLRW with Educational Community License v2.0 | 5 votes |
@Before public void init() throws OrgNotFoundException, LineItemNotFoundException { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(classController).build(); classController = new ClassController(lineItemService,null,null,null,resultService,null); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_TENANT_ADMIN")); UserContext context = UserContext.create(TestData.TENANT_1, "122", authorities); when(jwttoken.getPrincipal()).thenReturn(context); when(lineItemService.getLineItemsForClass("","","class123")).thenReturn(Collections.singletonList(li)); when(lineItemService.save("","", li, true)).thenReturn(li); }
Example #28
Source File: AnonymousAuthenticationProviderTest.java From gocd with Apache License 2.0 | 5 votes |
@Test void shouldAuthenticateRequest() { final AuthenticationToken<AnonymousCredential> authenticationToken = anonymousAuthenticationProvider.authenticate(null, null); assertThat(authenticationToken.getUser().getUsername()).isEqualTo("anonymous"); assertThat(authenticationToken.getCredentials()).isEqualTo(AnonymousCredential.INSTANCE); assertThat(authenticationToken.getUser().getAuthorities()) .containsExactly(GoAuthority.ALL_AUTHORITIES.toArray(new GrantedAuthority[0])); assertThat(authenticationToken.getAuthConfigId()).isNull(); assertThat(authenticationToken.getPluginId()).isNull(); }
Example #29
Source File: CalendarUserAuthorityUtils.java From Spring-Security-Third-Edition with MIT License | 5 votes |
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) { String username = calendarUser.getEmail(); if (username.startsWith("admin")) { return ADMIN_ROLES; } return USER_ROLES; }
Example #30
Source File: CalendarUserAuthorityUtils.java From Spring-Security-Third-Edition with MIT License | 5 votes |
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) { String username = calendarUser.getEmail(); if (username.startsWith("admin")) { return ADMIN_ROLES; } return USER_ROLES; }