当前位置: 首页 > 编程笔记 >

详解使用Spring Security OAuth 实现OAuth 2.0 授权

范稳
2023-03-14
本文向大家介绍详解使用Spring Security OAuth 实现OAuth 2.0 授权,包括了详解使用Spring Security OAuth 实现OAuth 2.0 授权的使用技巧和注意事项,需要的朋友参考一下

OAuth 2.0 是一种工业级的授权协议。OAuth 2.0是从创建于2006年的OAuth 1.0继承而来的。OAuth 2.0致力于帮助开发者简化授权并为web应用、桌面应用、移动应用、嵌入式应用提供具体的授权流程。

OAuth 2.0 is the industry-standard protocol for authorization. OAuth 2.0 supersedes the work done on the original OAuth protocol created in 2006. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices.

OAuth 2.0的四个角色

为了方便理解,以常用的 使用微信登录 为例

Resource Owner

资源拥有者,对应微信的每个用户微信上设置的个人信息是属于每个用户的,不属于腾讯

Resource Server

资源服务器,一般就是用户数据的一些操作(增删改查)的REST API,比如微信的获取用户基本信息的接口。

Client Application

第三方客户端,对比微信中就是各种微信公众号开发的应用,第三方应用经过 认证服务器 授权后即可访问 资源服务器 的REST API来获取用户的头像、性别、地区等基本信息。

Authorization Server

认证服务器,验证第三方客户端是否合法。如果合法就给客户端颁布token,第三方通过token来调用资源服务器的API。

四种授权方式(Grant Type)

anthorization_code

授权码类型,适用于Web Server Application。模式为:客户端先调用 /oauth/authorize/ 进到用户授权界面,用户授权后返回 code ,客户端然后根据code和 appSecret 获取 access token 。

implicit简化类型,相对于授权码类型少了授权码获取的步骤。客户端应用授权后认证服务器会直接将access token放在客户端的url。客户端解析url获取token。这种方式其实是不太安全的,可以通过 https安全通道 和 缩短access token的有效时间 来较少风险。

password

密码类型,客户端应用通过用户的username和password获access token。适用于资源服务器、认证服务器与客户端具有完全的信任关系,因为要将用户要将用户的用户名密码直接发送给客户端应用,客户端应用通过用户发送过来的用户名密码获取token,然后访问资源服务器资源。比如支付宝就可以直接用淘宝用户名和密码登录,因为它们属于同一家公司,彼此 充分信任 。

client_credentials

客户端类型,是不需要用户参与的一种方式,用于不同服务之间的对接。比如自己开发的应用程序要调用短信验证码服务商的服务,调用地图服务商的服务、调用手机消息推送服务商的服务。当需要调用服务是可以直接使用服务商给的 appID 和 appSecret 来获取token,得到token之后就可以直接调用服务。

其他概念

  1. scope :访问资源服务器的哪些作用域。
  2. refresh token :当access token 过期后,可以通过refresh token重新获取access token。

实现

有的时候资源服务器和认证服务器是两个不同的应用,有的时候资源服务器和认证服务器在通一个应用中,不同之处在于资源服务器是否需要检查token的有效性,前者需要检查,后者不需要。这里实现后者。

Application的安全配置

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()
        .and().csrf().disable()
        .authorizeRequests().anyRequest().authenticated();
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    super.configure(web);
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("lyt").password("lyt").authorities("ROLE_USER")
        .and().withUser("admin").password("admin").authorities("ROLE_ADMIN");
  }

  @Bean
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }
}

认证服务器配置

@EnableAuthorizationServer
@Configuration
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory().withClient("client")
        .scopes("read","write")
        .secret("secret")
        .authorizedGrantTypes("authorization_code","password","implicit","client_credentials");}

  @Override
  public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    super.configure(security);
  }

  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager);
  }

  @Autowired
  @Qualifier("authenticationManagerBean")
  private AuthenticationManager authenticationManager;
}

资源服务器配置

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableResourceServer
@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
 @Override
 public void configure(HttpSecurity http) throws Exception {
 http.antMatcher("/oauth2/api/**").authorizeRequests()
  .antMatchers(HttpMethod.GET, "/read/**").access("#oauth2.hasScope('read')")
  .antMatchers(HttpMethod.POST, "/write/**").access("#oauth2.hasScope('write')")
  .antMatchers(HttpMethod.PUT, "/write/**").access("#oauth2.hasScope('write')")
  .antMatchers(HttpMethod.DELETE, "/write/**").access("#oauth2.hasScope('write')");
 }

}

资源服务器 filter-order 设置

需要在 application.yml 中将filter-order设置成3,具体原因参考链接

防止cookie冲突

为了避免认证服务器的cookie和客户端的cookie冲突,出现错误,最好修改 cookie name 或者设置 contextPath 。

测试

postman 中提供OAuth 2.0的认证方式,可以获取到token之后再把认证加入http请求中,即可请求资源服务器的REST API

客户端信息

授权


获取的token


访问资源服务器API


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持小牛知识库。

 类似资料:
  • 我们必须在我的客户项目中集成OAuth2.0授权代码授予。目前,该应用程序使用本地登录页面。我们需要删除该页面,并将未登录的用户重定向到AS登录页面,。在AS end成功登录后,我们将被重定向到配置的。此时,我的客户端应用程序将如何知道用户已在AS登录?如何在客户端维护会话?另外,我需要用和访问令牌交换auth代码,并将其用于后续的服务器API调用。那么如何实现这一点并将令牌作为标头发送呢? 应用

  • 但是,在谈到安全性时,尝试为api网关实现oauth。但是现在我在Spring1.x版本中用来获取访问令牌的'oauth/token'endpoint在SpringBoot2中无法工作。 当我在谷歌搜索时,spring Boot2对spring security 5进行了一些更改,使其默认加密和解密 客户端ID 客户端-机密 用户密码 {“时间戳”:“2018-06-28T17:31:07.181

  • 目标:Java授权服务器: OAuth2.0授权代码授予细粒度权限流(不仅仅是SSO服务器) 用户管理和身份验证:自定义数据库 客户端管理和身份验证:KeyCloak 在开发中应该使用什么Keycloak适配器/API? 如果用户要出现在Keycloak中,应该如何管理/显示它们? 我是Keycloak的初学者,虽然我认为我理解主要原理,但它似乎是一个丰富的工具,我担心我可能仍然在使用它的最佳方法

  • 什么是授权Key 授权Key是在线开发中使用的应用密钥,即Key,它是服务的口令标识,是一种为了保障用户发布在云平台的服务的安全机制。 如果需要使用SuperMap Online的在线服务、API等资源进行在线Web开发,您需要先申请密钥key。key是服务的口令标识,由24位随机字母+数字组成,是一种在线服务的保护机制。 申请key 任何用户登录后,都可以申请开发key。 其中,根据key的具体

  • 本文向大家介绍详解laravel passport OAuth2.0的4种模式,包括了详解laravel passport OAuth2.0的4种模式的使用技巧和注意事项,需要的朋友参考一下 参考: https://xueyuanjun.com/post/ 1... 熟悉的场景 某个网站,某用户未注册,注册时提示可微信账号登录(github, google都有类似 某网站是第三方(客户端), 认证

  • 我想使用PHP实现多个授权,以便与Telegram REST API进行交互。 我要解决的是什么任务?嗯,很简单:几十个用户(他们都有一个carma(+10,-2,+1000等),有相关的组分类:web-masters和customers)在我的网站上有一个用户配置文件。在他们达到一定数量的carma之后,并且由于他们在他们的个人资料中被授权,他们就会加入到基于自动生成的电报的私人聊天中。 经过一