本文基于Spring Boot OAuth2,为您介绍OAuth的SDK示例和相关配置。
前提条件
修改配置文件
参考Spring Boot and OAuth2文档及示例,配置文件主要做以下两点修改。
在项目的src/main/resources目录下创建application.yml或 application.yaml,它是Spring Boot项目的核心配置文件,具体配置如下。
spring: security: oauth2: client: registration: aliyun: client-id: 415195082384692**** client-secret: 6EwN4qutnZuchG6n677Ie33SsjAhwyTpcOMSoIo6v0gqJtw4QcHhERVXfqzc**** client-authentication-method: client_secret_basic authorization-grant-type: authorization_code redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}" client-name: aliyun provider: aliyun: authorization-uri: https://signin.aliyun.com/oauth2/v1/auth token-uri: https://oauth.aliyun.com/v1/token user-info-uri: https://oauth.aliyun.com/v1/userinfo user-name-attribute: sub jwk-set-uri: https://oauth.aliyun.com/v1/keys
在pom.xml添加如下依赖配置。
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.18</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.3.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator-core</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>js-cookie</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> </dependencies>
完整代码示例
后端代码示例
基于Spring Security后端框架实现一个安全的Web应用程序,包括处理认证、授权、错误处理和CSRF防护。以下示例中,定义了一个RESTful API控制器WebApplication,该控制器处理HTTP请求并与OAuth2认证系统集成。
定义了一个私有变量handler,这是一个AuthenticationEntryPointFailureHandler的实例,用于处理认证入口点失败的情况。当用户尝试访问需要认证的页面,但认证失败时,这个处理器会设置HTTP状态码为401(未授权),并返回"Unauthorized"错误消息。
WebApplication类提供了一个GET映射
/user
,这个方法会在用户访问/user
路径时被调用。它接收一个OAuth2User对象作为参数,这个对象代表了当前经过认证的用户的OAuth2信息。方法返回一个包含用户名的Map对象,用户名是从OAuth2User对象的属性中获取的。在configure方法中,WebApplication类配置了HttpSecurity对象,以实现Web应用程序的安全策略。它首先配置了允许匿名访问的路径,包括根路径
/
、错误页面/error
和webjars
下的资源文件。然后,它配置了对其他所有请求进行身份验证,这意味着只有经过认证的用户才能访问这些路径。configure方法还配置了异常处理,当发生未授权异常时,会返回401状态码,并使用之前定义的handler来处理认证失败的情况。接下来,configure方法配置了OAuth2登录功能,包括登录失败的处理。如果登录失败,会在用户会话中设置错误消息,并调用handler来处理失败情况。
configure方法配置了注销功能,设置了注销成功后用户将被重定向到根路径
/
,并且这个操作对所有用户都是允许的。configure方法还配置了CSRF防护,使用CookieCsrfTokenRepository来存储CSRF令牌,并禁用了HttpOnly属性,以增加安全性。error方法是一个额外的GET映射,用于处理错误请求。它从用户会话中获取错误消息,并在返回错误消息之前将其从会话中移除。这样,错误消息就不会被重复显示给用户。
import org.springframework.boot.SpringApplication; import org.springframework.http.HttpStatus; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.web.authentication.AuthenticationEntryPointFailureHandler; import org.springframework.security.web.authentication.HttpStatusEntryPoint; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletRequest; import java.util.Collections; import java.util.Map; public class WebApplication extends WebSecurityConfigurerAdapter { private AuthenticationEntryPointFailureHandler handler = new AuthenticationEntryPointFailureHandler((request, response, authException) -> response.sendError(401, "Unauthorized")); @GetMapping("/user") public Map<String, Object> user(@AuthenticationPrincipal OAuth2User principal) { return Collections.singletonMap("name", principal.getAttribute("name")); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests(a -> a .antMatchers("/", "/error", "/webjars/**").permitAll() .anyRequest().authenticated() ) .exceptionHandling(e -> e .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)) ) .oauth2Login(o -> o .failureHandler((request, response, exception) -> { request.getSession().setAttribute("error.message", exception.getMessage()); handler.onAuthenticationFailure(request, response, exception); }) ) .logout(l -> l .logoutSuccessUrl("/").permitAll() ) .csrf(c -> c .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) ); } @GetMapping("/error") public String error(HttpServletRequest request) { String message = (String) request.getSession().getAttribute("error.message"); if (message != null) { request.getSession().removeAttribute("error.message"); } return message; } }
前端代码示例
在项目的src/main/resources/static目录下创建index.html页面,以便校验,代码示例如下。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Demo</title>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width"/>
<base href="/"/>
<link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css"/>
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/bootstrap/js/bootstrap.min.js"></script>
<script src="/webjars/js-cookie/js.cookie.js">
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (settings.type === 'POST' || settings.type === 'PUT' || settings.type === 'DELETE') {
if (!(/^(http:\/\/|https:\/\/)/.test(settings.url))) {
xhr.setRequestHeader("X-XSRF-TOKEN", Cookies.get('XSRF-TOKEN'));
}
}
}
});
</script>
</head>
<body>
<h1>Demo</h1>
<div class="container text-danger error"></div>
<script>
$.get("/error", function (data) {
if (data) {
$(".error").html(data);
} else {
$(".error").html('');
}
});
</script>
<div class="container unauthenticated">
With Aliyun: <a href="/oauth2/authorization/aliyun">click here</a>
</div>
<div class="container authenticated">
With Google:<a href="/oauth2/authorization/google">click here</a>
</div>
<script type="text/javascript">
$.get("/user", function(data) {
$("#user").html(data.name);
$(".unauthenticated").hide()
$(".authenticated").show()
});
</script>
<div class="container authenticated">
Logged in as: <span id="user"></span>
<div>
<button onClick="logout()" class="btn btn-primary">Logout</button>
</div>
</div>
<script type="text/javascript">
var logout = function() {
$.post("/logout", function() {
$("#user").html('');
$(".unauthenticated").show();
$(".authenticated").hide();
})
return true;
}
</script>
</body>
</html>
结果验证
运行WebApplication代码示例,项目启动后在浏览器中访问http://localhost:8080
。