一 进行授权页

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

三 授权资源类型

登陆成功后,去授权你的资源,这些资源是在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. mq解决分布式事物问题【代码】

    上节课简单说了一下mq是怎么保证数据一致性的.下面直接上代码了. 所需环境:1.zookeepor注册中心   2.kafka的服务端和工具客户端(工具客户端也可以不要只是为了更方便的查看消息而已)  ...

  2. DRF Django REST framework 之 序列化(三)

    Django 原生 serializer (序列化) 导入模块 from django.core.serializers import serialize 获取queryset 对queryset进行 ...

  3. luogu P5514 [MtOI2019]永夜的报应

    题目背景 在这世上有一乡一林一竹亭,也有一主一仆一仇敌. 有人曾经想拍下他们的身影,却被可爱的兔子迷惑了心神. 那些迷途中的人啊,终究会消失在不灭的永夜中-- 题目描述 蓬莱山 辉夜(Kaguya)手 ...

  4. NRF5340首款双核处理器无线SoC

    nRF5340基于Nordic经过验证并在全球范围广泛采用的nRF51和nRF52系列多协议SoC而构建,同时引入了具有先进安全功能的全新灵活双处理器硬件架构,支持包括蓝牙5.1/低功耗蓝牙 (Blu ...

  5. Undefined symbols for architecture x86_64"_OBJC_CLASS_$_QQApiInterface 怎么搞

    今天上午报了一个这样的错误 解决办法 如此如此 ~~ 然后编译 看看报的什么错误 还是不行的话就重新导入三方库 添加依赖库 结果build success

  6. 压缩感知重构算法之IHT算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  7. Zookeeper Watcher接口

    在ZooKeeper中,接口类Watcher用于表示一个标准的事件处理器,其定义了事件通知相关的逻辑,包含KeeperState和EventType两个枚举类,分别代表了通知状态和事件类型,同时定义了 ...

  8. AutoCAD中的螺旋究竟是什么螺旋?

    AutoCad从很早的时候就开始提供了螺旋线的功能,它的用法相对简单,非常适合用来对等距螺旋的理论进行演练. 选择螺旋线工具,首先画出一个基准圆,再向内(或向外)移动鼠标,拖出一个旋转3个周期的螺旋. ...

  9. HashMap的常见问题

    关于HashMap的一些常见的问题,自己总结一下: 首选HashMap在jdk1.7和jdk1.8里面的实现是不同的,在jdk1.7中HashMap的底层实现是通过数组+链表的形式实现的,在jdk1. ...

  10. Orleans 配置端口的一些坑

    Orleans的配置有点乱的 整理了下 .Configure<EndpointOptions>(options => { //这里的IP决定了是本机 还是内网 还是公网 option ...