何为oauth2
OAuth(开放授权)是一个开放标准,允许用户授权第三方移动应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容,OAuth2.0是OAuth协议的延续版本,但不向后兼容OAuth 1.0即完全废止了OAuth1.0。应用场景为第三方登录、APP授权、前后端分离授权等。详细介绍可以参考阮一峰老师的介绍:http://www.ruanyifeng.com/blog/2019/04/oauth_design.html
基本配置
项目中需要增加spring-security-oauth2 的依赖。配置类继承AuthorizationServerConfigurerAdapter 实现配置
@Configuration
@EnableAuthorizationServer
public class OAuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("SampleClientId") // clientId, 可以类比为用户名
.secret(passwordEncoder.encode("secret")) // secret, 可以类比为密码
.authorizedGrantTypes("authorization_code") // 授权类型,这里选择授权码
.scopes("user_info") // 授权范围
.autoApprove(true) // 自动认证
.redirectUris("http://localhost:8882/login","http://localhost:8883/login") // 认证成功重定向URL
.accessTokenValiditySeconds(10); // 超时时间,10s
}
}
全局的安全配置
@Configuration
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login")
.antMatchers("/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll() // 自定义登录页面,这里配置了 loginPage, 就会通过 LoginController 的 login 接口加载登录页面
.and().csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 配置用户名密码,这里采用内存方式,生产环境需要从数据库获取
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("123"))
.roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
其他深入配置,之后再补充