我使用Spring Boot 2
+ Spring Security
。我创建了简单的AuthorizationServer
:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfigJwt extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("sampleClientId")
.and()
.withClient("fooClientIdPassword").secret(passwordEncoder().encode("secret"))
.authorizedGrantTypes("password", "authorization_code", "refresh_token").scopes("read", "write")
.accessTokenValiditySeconds(3600) // 1 hour
.refreshTokenValiditySeconds(2592000);// 30 days
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager)
.accessTokenConverter(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("as466gf");
return converter;
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
我使用Angular
。在我的有角度的应用程序中,我想为用户区分一些功能。例如,管理员可以创建新闻,而普通用户则不能。分别,对于管理员,我需要显示添加按钮,而对于所有其他按钮,则需要隐藏。例如:
<button type="button" id="add-news-btn" pButton icon="ui-icon-add" label="Add"
class="green-btn tool-btn" routerLink="/news/new"></button>
但是我不知道该怎么做。在后端方面,我可以像这样在控制器上设置作用域和角色:
@PreAuthorize("#oauth2.hasScope('write') and hasRole('ROLE_ADMIN')")
但是我如何在前端获得用户权限,以便可以操纵显示或隐藏之类的html元素?