SpringSecurity + Oauth2的配置和使用
如何使用SpringSecurity和Oauth2去实现一个安全配置(四大模式之授权码模式)?
1.导入依赖
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2.配置类
//SpringSecurity的配置类 放行/oauth/,后续需要获取token 必须开启 protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/oauth/**","/login/**") .permitAll() .anyRequest() .authenticated() .and() .formLogin() .permitAll(); }
//授权服务器的配置 @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { //配置客户端信息 clients.inMemory() .withClient("user") .secret(passwordEncoder.encode("123123")) .accessTokenValiditySeconds(3600) //授权成功后跳转的地址,后面携带授权码 .redirectUris("http://www.baidu.com") //授权范围 .scopes("all") //授权类型,授权码 .authorizedGrantTypes("authorization_code"); }
//资源服务器配置 @Configuration @EnableResourceServer public class ResouceServer extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest() .authenticated() .and() .requestMatchers() //配置了以下路径之后,只有携带token才可以访问 .antMatchers("/user/**","/test/**"); } }
3.获取授权码
http://localhost:8080/oauth/authorize?response_type=code&client_id=user¤t_uri=http://www.baidu.com
发送以上请求之后先会跳到springsecurity的登录界面,登录之后就会执行以上请求,成功后跳转到http://www.baidu.com?code=授权码
4.获取token
可以使用postman工具去发送请求http://localhost:8080/oauth/token,请求方式设为post,把Authorization的Type设为Basic Auth 右侧填写客户端用户名和密码 ,Body里面添加 以下键值对: key value grant_type authorization_code code 第三步生成的授权码 client_id user redirect_uri http://www.baidu.com
点击发送 ,就会生成一个token
5.到资源服务器下获取资源
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
微信-小程序调用云服务