一 进行授权页

 
二 使用资源站用户登陆
自动跨到资源登陆页,先登陆

三 授权资源类型

登陆成功后,去授权你的资源,这些资源是在AuthorizationServerConfig.configure方法里配置的
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(ClientID)
.secret(passwordEncoder.encode(ClientSecret))
.authorizedGrantTypes("authorization_code", "refresh_token",
"password", "implicit")
.scopes("read","write","del","userinfo")
.redirectUris(RedirectURLs);
}

四 接到code

授权之后,系统会重定向到你的redirect_uri这个页面,并带上唯一的code

五 获取access_token

我们拿着code就要再去授权服务器去获取token了,你可以在你的代码里写这个,也可以手动拿着code,去拼成一个url,再去拿token,就像这下面的实例。
注意向oauth/token发的是post请求,client_id和client_secret如果在url上传递,如果在AuthorizationServerConfig类的configure方法中开启allowFormAuthenticationForClients,代码如下
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("isAuthenticated()")
.checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();//支持把secret和clientid写在url上,否则需要在头上
}
然后请求后给有下面的响应
Authorization Ccode------RFRLFY
access_token_url http://localhost:8081/oauth/token?client_id=android1&code=RFRLFY&grant_type=authorization_code&redirect_uri=http://localhost:8081/callback&client_secret=android1
Access Token Response ---------{"access_token":"faadf3bf-6488-4036-bc3b-21b0a979602c","token_type":"bearer","refresh_token":"1b01f133-c5ab-419f-8125-088c85916ecb","expires_in":,"scope":"read"}

回调页面代码,主要实现了对code的获取,对access_token的组织,然后请求时把access_token带上,这个方法一般会做成公用的过滤器

@Controller
public class UserController {
@RequestMapping(value = "/callback", method = RequestMethod.GET)
public ResponseEntity<String> callback(@RequestParam("code") String code) throws JsonProcessingException, IOException {
ResponseEntity<String> response = null;
System.out.println("Authorization Ccode------" + code);
RestTemplate restTemplate = new RestTemplate();
String access_token_url = "http://localhost:8081/oauth/token";
access_token_url += "?client_id=android1&code=" + code;
access_token_url += "&grant_type=authorization_code";
access_token_url += "&redirect_uri=http://localhost:8081/callback";
access_token_url += "&client_secret=android1";
System.out.println("access_token_url " + access_token_url);
response = restTemplate.exchange(access_token_url, HttpMethod.POST, null, String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(response.getBody());
String token = node.path("access_token").asText(); System.out.println("access_token" +access_token);
    String url = "http://localhost:8081/index"; HttpHeaders headers1 = new HttpHeaders(); headers1.add("Authorization", "Bearer " + token); HttpEntity<String> entity = new HttpEntity<>(headers1); ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); return result; }

六 拿着access_token去请求具体的资源

可以在url地址上直接:http://localhost:8081/index?access_token=faadf3bf-6488-4036-bc3b-21b0a979602c
七 如何开启oauth scopes授权
.access("#oauth2.hasScope('del')") 这个需要在ResourceServerConfig.configure里添加它,例如下载代码
@Configuration
@EnableResourceServer
@Order(6)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()//禁用了 csrf 功能
.authorizeRequests()//限定签名成功的请求
.antMatchers("/index").access("#oauth2.hasScope('del')") //授权码scopes里需要选中del才可以访问
.antMatchers("/user").authenticated()//签名成功后可访问,不受role限制
.anyRequest().permitAll()//其他没有限定的请求,允许访问
.and().anonymous()//对于没有配置权限的其他请求允许匿名访问
.and().formLogin()//使用 spring security 默认登录页面
.and().httpBasic();//启用http 基础验证 }
}

八  需要注意的地方

如果你对用户进行了角色和权限的配置,对于某些保护接口需要有指定权限才能访问的话,需要重getAuthorities方法,否则,你的权限将会失效!

@Entity
@Data
public class User extends BaseEntity implements UserDetails {
@Id
@GeneratedValue
private Long id;
private String username;
private String password;
private String firstName;
private String lastName;
@Email
private String email;
private String imageUrl; @JsonIgnore
@ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
@BatchSize(size = 20)
private Set<Role> roles = new HashSet<>(); @Transient
private Set<GrantedAuthority> authorities = new HashSet<>(); /**
* 注意,这块需要加@Override重写,否则权限无效.
*
* @return
*/
@Override
public Set<GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<>();
for (Role role : this.roles) {
for (Authority authority : role.getAuthorities()) {
authorities.add(new SimpleGrantedAuthority(authority.getValue()));
}
}
return authorities;
} @Override
public boolean isAccountNonExpired() {
return true;
} @Override
public boolean isAccountNonLocked() {
return true;
} @Override
public boolean isCredentialsNonExpired() {
return true;
} @Override
public boolean isEnabled() {
return true;
}
}

感谢阅读!

springboot2.x实现oauth2授权码登陆的更多相关文章

  1. 13.详解oauth2授权码流程

    13.详解oauth2授权码流程 把登陆系统单独独立出来,可以给自己写的微服务用,也可以给第三方的系统调用我们的服务 显式的和隐式的,两种方式,

  2. 阶段5 3.微服务项目【学成在线】_day16 Spring Security Oauth2_06-SpringSecurityOauth2研究-Oauth2授权码模式-申请令牌

    3.3 Oauth2授权码模式 3.3.1 Oauth2授权模式 Oauth2有以下授权模式: 授权码模式(Authorization Code) 隐式授权模式(Implicit) 密码模式(Reso ...

  3. Spring Security OAuth2 授权码模式

     背景: 由于业务实现中涉及到接入第三方系统(app接入有赞商城等),所以涉及到第三方系统需要获取用户信息(用户手机号.姓名等),为了保证用户信息的安全和接入方式的统一, 采用Oauth2四种模式之一 ...

  4. 微信授权就是这个原理,Spring Cloud OAuth2 授权码模式

    上一篇文章Spring Cloud OAuth2 实现单点登录介绍了使用 password 模式进行身份认证和单点登录.本篇介绍 Spring Cloud OAuth2 的另外一种授权模式-授权码模式 ...

  5. 阶段5 3.微服务项目【学成在线】_day16 Spring Security Oauth2_07-SpringSecurityOauth2研究-Oauth2授权码模式-资源服务授权测试

    下面要完成  5.6两个步骤 3.3.4 资源服务授权 3.3.4.1 资源服务授权流程 资源服务拥有要访问的受保护资源,客户端携带令牌访问资源服务,如果令牌合法则可成功访问资源服务中的资 源,如下图 ...

  6. asp.net利用QQ邮箱发送邮件,关键在于开启pop并设置授权码为发送密码

    public static bool SendEmail(string mailTo, string mailSubject, string mailContent)        {         ...

  7. oAuth2授权协议 & 微信授权登陆和绑定 & 多环境共用一个微信开发平台回调设置

    OAuth2(open Auth)开放授权协议 授权码模式流程: 1.浏览器(客户端)点击一个比如使用微信登陆按钮 2.会跳到认证服务器页面,让用户选择是否授权 3.如果用户点击授权,那么会跳转到开始 ...

  8. Spring Cloud2.0之Oauth2环境搭建(授权码模式和密码授权模式)

    oauth2 server 微服务授权中心,    github源码  https://github.com/spring-cloud/spring-cloud-security 对微服务接口做一些权 ...

  9. Oauth2.0认证---授权码模式

    目录: 1.功能描述 2.客户端的授权模式 3.授权模式认证流程 4.代码实现 1.功能描述 OAuth在"客户端"与"服务提供商"之间,设置了一个授权层(au ...

随机推荐

  1. ThinkPHP5——模型关联(一对一关联)

    定义 定义一对一关联使用了hasOne,hasOne方法的参数包括: hasOne('关联模型名','外键名','主键名',['模型别名定义'],'join类型'); 下面定义一个用户表,公司给每个用 ...

  2. MyBatis的配置与使用(增,删,改,查)

    ---恢复内容开始--- Mybatis入门介绍 一.MyBatis介绍 什么是MyBtis? MyBatis 是一个简化和实现了 Java 数据持久化层(persistence layer)的开源框 ...

  3. Android多图选择

    多图选择是Android中一个常用的功能,用户可以拍照或者批量选择图片上传,还是国际惯例,先看下效果图,demo地址我会放到文章末尾. 经过对比,这里我选择了一个第三方开源库PictureSelect ...

  4. Java修炼——接口详解_接口的特征_使用接口的意义

    接口中可以包含的内容: 抽象法和非抽象方法(jdk1.8,必须使用default的关键字),属性(public static final)常量. 接口和类的关系 1.(继承了接口)类必须去实现接口中的 ...

  5. JQuery中操作元素的属性_对象属性

    我们主要是通过attr去获取元素的属性: 看body内容: <body> <p> 账号:<input type="text" id="una ...

  6. C# 利用反射更改父类公开对象

    需求 : 有一个保存数据库字段的基础类,现在要加个状态返回给前端,但是又不能改基础类: class BaseA { public string Name { get; set; } } class A ...

  7. usb2.0高速视频采集之68013A寄存器配置说明

    任何的固件编程离不开与与原理图参考,图纸中所采用的是USB的Slave_fifo传输方式,具体配置与图纸对应即可. •USB_IFCLK:同步Slave_FIFO模式,输入频率范围5M-48M,在FP ...

  8. 【集合系列】- 深入浅出分析 ArrayDeque

    一.摘要 在 jdk1.5 中,新增了 Queue 接口,代表一种队列集合的实现,咱们继续来聊聊 java 集合体系中的 Queue 接口. Queue 接口是由大名鼎鼎的 Doug Lea 创建,中 ...

  9. matplotlib可视化最全指南

    1. 折线图:plt.plot 设置数据:plt.plot(x,y),单列数据传入默认y轴,此时x轴数据默认从0逐渐对应递增 设置颜色:plt.plot(x,y,color/c=" &quo ...

  10. java程序员面试经历(不忘初心,永不放弃,方得始终)。

    其实一直想静下心好好写一点博客,记录下青春,但一直忙于学习,写bug.....转眼间2017只剩下最后几天,岁月无情划过,不留痕迹,唯有稀疏地中海.哈哈,本篇文章主要是想分享下刚毕业入门找工作的一点小 ...