Spring中基于OAuth2的认证和授权是什么
时间:2020-02-23 14:34:43 来源:igfitidea点击:
OAuth2允许第三方应用程序接收对HTTP服务的有限访问,该服务或者代表资源所有者,或者允许第三方应用程序以自己的名义获得访问权。多亏了OAuth2,服务提供商和消费者应用程序可以安全地相互交互。
工作流
在从外部应用程序访问用户的受保护数据之前,需要执行几个步骤。
用户被带到服务提供商服务器
e、 g.Facebook或者LinkedIn
用户必须向外部应用程序授予权限才能访问资源,例如读取或者甚至写入与他/她的数据相关的资源。
授权服务器正在将访问令牌发送到消费者应用程序。
现在,外部应用程序可以从资源服务器访问用户的受保护数据。
不同角色的术语
在OAuth2中,有4个角色:
资源所有者
用户
资源服务器
托管受保护资源并基于访问令牌提供对其的访问的服务器
顾客
寻求许可的外部应用程序
授权服务器
在对用户进行身份验证后发出访问令牌
不同的代币
令牌有两种类型:
访问令牌
由授权服务器根据用户身份验证提供
允许第三方应用程序访问用户数据
刷新令牌
用于在原始令牌过期时获取新的访问令牌,因此该名称
但是,由于安全原因,并不总是能够获得此令牌
@EnableOAuth2Sso
@Configuration
@EnableZuulProxy
@EnableOAuth2Sso
@Order(value = 0)
public class AppConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private ResourceServerTokenServices resourceServerTokenServices;
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/auth-server/**", "/login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/");
}
}
@enableauth2sso注释通知Spring给conifugre一个OAuth2TokenRelayFilter。此筛选器从用户的HTTP会话检索已获得的访问令牌并填充它们。
@Order注释的作用是确保我们的WebSecurityConfigurerAdapter创建的过滤器优先于另一个WebSecurityConfigurerAdapter创建的过滤器。
@EnableResourceServer
现在,让我们设置资源服务器。
@SpringBootApplication
@EnableResourceServer
@Controller
@RequestMapping("/")
class ResourceServerImplementation {
public static void main(String[] args) {
SpringApplication.run(ResourceServerImplementation.class, args);
}
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String greetPrincipal(Principal principal) {
return "Greetings, " + principal.getName();
}
}
此应用程序返回发起该请求的主体的名称。同样,我们需要一个有效的访问令牌来访问资源服务器的端点。
这两个代码片段取自这里

