81,095
社区成员
发帖
与我相关
我的任务
分享
@Configuration
@EnableAuthorizationServer //配置 授权服务
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
/**
* test
* 为了使用“password”授权方式,我们需要通过spring的@Autowired注解来注入和使用AuthenticationManager bean
* @return
*/
@Autowired //去掉 Autowired 不支持 grant_type =passwpd (添加后: invalid_grant Bad credentials)
@Qualifier("authenticationManagerBean") //添加后 启动报错,注入不了
private AuthenticationManager authenticationManager;
/**/
@Bean
public TokenStore tokenStore(){
return new InMemoryTokenStore();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("tonr").secret("secret")
.autoApprove(true) //test
.authorizedGrantTypes("password", "authorization_code", "client_credentials")
.scopes("read");
// .accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
// refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
// .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit" client_credentials)
}
/**
* test
* @param security
* @throws Exception
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
*/
/**
* test
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);
}
}
@Configuration
@EnableResourceServer // 配置授权资源路径
@Order(6)
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
/**
* test
@Autowired
TokenStore tokenStore;
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId("app").stateless(false);//.tokenStore(tokenStore);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/se")
.and()
.authorizeRequests()
.antMatchers("/se").access("#oauth2.hasScope('read')");
}
}
@EnableAuthorizationServer
@Order(2)
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
/**
* test
* @return
* @throws Exception
*/
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
//.and()
// .formLogin()
.and()
.httpBasic()
;
}
}