栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

OAuth2.0授权码模式入门Demo

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

OAuth2.0授权码模式入门Demo

代码地址

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

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

代码 依赖

	org.springframework.boot
	spring-boot-starter-security

 

    org.springframework.security.oauth
    spring-security-oauth2
    2.3.4.RELEASE

或者 引入spring cloud oauth2依赖


    org.springframework.cloud
    spring-cloud-starter-oauth2

 


    
        
            org.springframework.cloud
            spring-cloud-dependencies
            Hoxton.SR8
            pom
            import
        
    

配置 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


账号 fox 密码 123456

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

登录成功之后获取授权码

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

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

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

获取token令牌

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

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


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


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


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

调用成功之后postman返回:

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

访问指定接口 访问方式1:请求头携带token

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

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

或者浏览器访问:

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

implicit简化模式 登录

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

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

获取access_token

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

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

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

访问指定的接口

http://localhost:8080/user/getCurrentUser

请求头携带:

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

发现能正常访问

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/731367.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号