當前位置: 首頁>>代碼示例>>Java>>正文


Java AuthorityUtils類代碼示例

本文整理匯總了Java中org.springframework.security.core.authority.AuthorityUtils的典型用法代碼示例。如果您正苦於以下問題:Java AuthorityUtils類的具體用法?Java AuthorityUtils怎麽用?Java AuthorityUtils使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


AuthorityUtils類屬於org.springframework.security.core.authority包,在下文中一共展示了AuthorityUtils類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getAuthentication

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
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;
}
 
開發者ID:Clcanny,項目名稱:MicroServiceDemo,代碼行數:18,代碼來源:JwtTokenUtil.java

示例2: requestHeaderAuthenticationFilter

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
@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;
}
 
開發者ID:syndesisio,項目名稱:syndesis,代碼行數:18,代碼來源:SecurityConfiguration.java

示例3: mapUserEntityToUserDetails

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
private UserDetails mapUserEntityToUserDetails(UserEntity userEntity) {
	List<GrantedAuthority> authorities = AuthorityUtils.NO_AUTHORITIES;
	if (userEntity.getRoles() != null && userEntity.getRoles().size() > 0) {

		authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
				userEntity.getRoles().stream().map(r -> r.getScope().name()+":"+r.getName()).collect(Collectors.joining(","))
		);
	}

	io.gravitee.management.idp.api.authentication.UserDetails userDetails = new io.gravitee.management.idp.api.authentication.UserDetails(
			userEntity.getUsername(), userEntity.getPassword(), authorities);

	userDetails.setFirstname(userEntity.getFirstname());
	userDetails.setLastname(userEntity.getLastname());
	userDetails.setEmail(userEntity.getEmail());
	userDetails.setSource(RepositoryIdentityProvider.PROVIDER_TYPE);
	userDetails.setSourceId(userEntity.getUsername());

	return userDetails;
}
 
開發者ID:gravitee-io,項目名稱:gravitee-management-rest-api,代碼行數:21,代碼來源:RepositoryAuthenticationProvider.java

示例4: configure

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
	ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder>.ClientBuilder builder = clients
			.inMemory().withClient(this.details.getClientId());
	builder.secret(this.details.getClientSecret())
			.resourceIds(this.details.getResourceIds().toArray(new String[0]))
			.authorizedGrantTypes(
					this.details.getAuthorizedGrantTypes().toArray(new String[0]))
			.authorities(
					AuthorityUtils.authorityListToSet(this.details.getAuthorities())
							.toArray(new String[0]))
			.scopes(this.details.getScope().toArray(new String[0]));
	if (this.details.getRegisteredRedirectUri() != null) {
		builder.redirectUris(
				this.details.getRegisteredRedirectUri().toArray(new String[0]));
	}
}
 
開發者ID:Nephilim84,項目名稱:contestparser,代碼行數:18,代碼來源:OAuth2AuthorizationServerConfiguration.java

示例5: configure

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
	ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder>.ClientBuilder builder = clients
			.inMemory().withClient(this.details.getClientId());
	builder.secret(this.details.getClientSecret())
			.resourceIds(this.details.getResourceIds().toArray(new String[0]))
			.authorizedGrantTypes(
					this.details.getAuthorizedGrantTypes().toArray(new String[0]))
			.authorities(
					AuthorityUtils.authorityListToSet(this.details.getAuthorities())
							.toArray(new String[0]))
			.scopes(this.details.getScope().toArray(new String[0]));

	if (this.details.getAutoApproveScopes() != null) {
		builder.autoApprove(
				this.details.getAutoApproveScopes().toArray(new String[0]));
	}
	if (this.details.getAccessTokenValiditySeconds() != null) {
		builder.accessTokenValiditySeconds(
				this.details.getAccessTokenValiditySeconds());
	}
	if (this.details.getRefreshTokenValiditySeconds() != null) {
		builder.refreshTokenValiditySeconds(
				this.details.getRefreshTokenValiditySeconds());
	}
	if (this.details.getRegisteredRedirectUri() != null) {
		builder.redirectUris(
				this.details.getRegisteredRedirectUri().toArray(new String[0]));
	}
}
 
開發者ID:spring-projects,項目名稱:spring-security-oauth2-boot,代碼行數:31,代碼來源:OAuth2AuthorizationServerConfiguration.java

示例6: oauth2ClientDetails

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
@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;
}
 
開發者ID:spring-projects,項目名稱:spring-security-oauth2-boot,代碼行數:17,代碼來源:OAuth2AuthorizationServerConfiguration.java

示例7: testAuthorizationServerOverride

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
@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);
}
 
開發者ID:spring-projects,項目名稱:spring-security-oauth2-boot,代碼行數:20,代碼來源:OAuth2AutoConfigurationTests.java

示例8: getAuthentication

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
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;
    }
 
開發者ID:hzwy23,項目名稱:hauth-java,代碼行數:25,代碼來源:JwtService.java

示例9: userDetailsService

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
@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 + "'");
        }
    };
}
 
開發者ID:dizitart,項目名稱:nitrite-database,代碼行數:19,代碼來源:DataGateSecurityConfigurer.java

示例10: runAs

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
/**
 * 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)));
}
 
開發者ID:Just-Fun,項目名稱:spring-data-examples,代碼行數:17,代碼來源:SecurityUtils.java

示例11: userDetailsService

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
@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 + "]不存在");
			}
		}
	};

}
 
開發者ID:leftso,項目名稱:demo-spring-boot-security-oauth2,代碼行數:20,代碼來源:SecurityConfiguration.java

示例12: getOauth2Request

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:anilallewar,項目名稱:microservices-basics-spring-boot,代碼行數:23,代碼來源:WithOAuth2MockAccessTokenSecurityContextFactory.java

示例13: getAuthentication

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
/**
 * Provide the mock user information to be used
 * 
 * @param withMockOAuth2Token
 * @return
 */
private Authentication getAuthentication(WithMockOAuth2Token withMockOAuth2Token) {
	List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities());

	User userPrincipal = new User(withMockOAuth2Token.userName(), withMockOAuth2Token.password(), true, true, true,
			true, authorities);

	HashMap<String, String> details = new HashMap<String, String>();
	details.put("user_name", withMockOAuth2Token.userName());
	details.put("email", "[email protected]");
	details.put("name", "Anil Allewar");

	TestingAuthenticationToken token = new TestingAuthenticationToken(userPrincipal, null, authorities);
	token.setAuthenticated(true);
	token.setDetails(details);

	return token;
}
 
開發者ID:anilallewar,項目名稱:microservices-basics-spring-boot,代碼行數:24,代碼來源:WithOAuth2MockAccessTokenSecurityContextFactory.java

示例14: userDetailsService

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
@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");
            }
        }
    };
}
 
開發者ID:2DV603NordVisaProject,項目名稱:nordvisa_calendar,代碼行數:24,代碼來源:WebSecurityConfig.java

示例15: setup

import org.springframework.security.core.authority.AuthorityUtils; //導入依賴的package包/類
@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")));
}
 
開發者ID:spring-projects,項目名稱:spring-session-data-mongodb,代碼行數:18,代碼來源:AbstractITest.java


注:本文中的org.springframework.security.core.authority.AuthorityUtils類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。