代码地址

代码是图灵学院的,我自己学完了之后把代码整理了一下,删掉了无用的代码,然后精简了一下

https://gitee.com/zjj19941/ZJJ_Neaten5.10/tree/master/ZJJ_SpringCloud_Oauth2/demo01

代码

依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-security</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.security.oauth</groupId>
  7. <artifactId>spring-security-oauth2</artifactId>
  8. <version>2.3.4.RELEASE</version>
  9. </dependency>

或者 引入spring cloud oauth2依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

<!-- spring cloud -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR8</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

配置 spring security

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().permitAll()
                .and().authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .anyRequest().authenticated()
                .and().logout().permitAll()
                .and().csrf().disable();
    }
}

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password = passwordEncoder.encode("123456");
        return new User("fox",password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}

@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        return authentication.getPrincipal();
    }
}

配置授权服务器

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置client_id
                .withClient("client")
                //配置client-secret
                .secret(passwordEncoder.encode("123123"))
                //配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                //配置刷新token的有效期
                .refreshTokenValiditySeconds(864000)
                //配置redirect_uri,用于授权成功后跳转
                .redirectUris("http://www.baidu.com")
                //配置申请的权限范围
                .scopes("all")
                //配置grant_type,表示授权类型
                .authorizedGrantTypes("authorization_code");
    }
}

配置资源服务器

@Configuration
@EnableResourceServer
public class ResourceServiceConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .anyRequest().authenticated()
        .and().requestMatchers().antMatchers("/user/**");

    }
}

测试

authorization_code模式

开始登录

http://localhost:8080/oauth/authorize?response_type=code&client_id=client 或者 http://localhost:8080/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://www.baidu.com&scope=all

image.png
账号 fox 密码 123456

这个账号密码是在下面的类写死的,实际情况是从关系型数据库里面查询出来
image.png

登录成功之后获取授权码

登录之后会自动重定向到百度页面, code=w6FkKd 就是授权码

image.png

为什么会重定向到百度呢?

因为在 授权服务器类上配置了redirectUris属性是百度

image.png

获取token令牌

根据授权码通过post请求获取

访问post请求: http://localhost:8080/oauth/token

image.png
body里面参数:
grant_type:authorization_code
code:w6FkKd
redirect_url:http://www.baidu.com

image.png

账号密码是 client 123123 ,这个是在代码里面下面的地方配置的

image.png
withClient的值是账号
secret的值是密码
redirectUris的值是跳转的url
authorizedGrantTypes就是grant_type

调用成功之后postman返回:
image.png

{
“access_token”: “f7c24754-85f2-4976-9617-a6de9940aec3”,
“token_type”: “bearer”,
“expires_in”: 576,
“scope”: “all”
}

访问指定接口

访问方式1:请求头携带token

image.png

Authorization:bearer f7c24754-85f2-4976-9617-a6de9940aec3

访问方式2:浏览器get请求后面拼接参数

或者浏览器访问:

http://localhost:8080/user/getCurrentUser?access_token=f7c24754-85f2-4976-9617-a6de9940aec3

image.png

implicit简化模式

登录

访问: http://localhost:8080/oauth/authorize?client_id=client&response_type=token&scope=all&redirect_uri=http://www.baidu.com

会直接重定向到下面页面上,输入账号密码 : 账号 fox 密码 123456
image.png

获取access_token

登录成功之后会跳到这个页面
image.png

点击Authorize按钮,点击完成之后会重定向到设置的百度页面,然后url会自动带access_token

https://www.baidu.com/#access_token=5370d3af-78c8-4c90-8e65-617ca4714d7c&token_type=bearer&expires_in=3599
image.png

访问指定的接口

http://localhost:8080/user/getCurrentUser

请求头携带:

Authorization:bearer 5370d3af-78c8-4c90-8e65-617ca4714d7c
image.png

发现能正常访问