Introduction
OAuth 2.0 is an authorization framework that enables third-party applications to access protected resources on behalf of a user without requiring the user’s credentials. This is achieved through the use of access tokens, which are issued by an OAuth provider and used by third-party applications to access the user’s resources.
Spring Boot is a popular framework for building web applications in Java. It provides a powerful set of tools for building secure and scalable web applications and is well-suited for implementing OAuth 2.0.
In this blog post, we will go through the steps required to implement OAuth 2.0 using Spring Boot. We will use the Spring Security OAuth 2.0 framework to implement OAuth 2.0 authorization and authentication.
Before we start, let’s first go through the OAuth 2.0 flow to get a better understanding of how it works.
Overview of OAuth 2.0
OAuth 2.0 is an authorization protocol that allows third-party applications to access resources on behalf of a user. It uses access tokens to provide access to resources, which are obtained after successful authentication. There are four roles in OAuth 2.0: Resource Owner, Client, Authorization Server, and Resource Server.
- Resource Owner: The user who owns the resource that is being accessed by the client.
2.Client: The application that is requesting access to the resource on behalf of the user.
3.Authorization Server: The server that issues access tokens to the client after successful authentication of the user.
4.Resource Server: The server that holds the resource that is being accessed by the client.
OAuth 2.0 Flow
The OAuth 2.0 flow involves the following steps:
User requests access to a protected resource from a third-party application.
The third-party application redirects the user to an OAuth provider to obtain an access token.
The user logs in to the OAuth provider and grants permission to the third-party application to access the protected resource.
The OAuth provider issues an access token to the third-party application.
The third-party application uses the access token to access the protected resource on behalf of the user.
Now that we have an understanding of the OAuth 2.0 flow, let’s move on to implementing it using Spring Boot.
Implementing OAuth 2.0 using Spring Boot
Add dependencies
First, add the necessary dependencies to your Spring Boot project. You can do this by adding the following dependencies to your pom.xml file:
`
org.springframework.boot
spring-boot-starter-oauth2-client
org.springframework.security
spring-security-oauth2-jose
`
Configure OAuth 2.0
Next, configure OAuth 2.0 by creating a class that extends WebSecurityConfigurerAdapter. Here's an example:
`@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/oauth2/**", "/login/**", "/logout/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .loginPage("/login") .defaultSuccessURL("/home") .and() .logout() .logoutSuccessUrl("/") .logoutUrl("/logout") .and() .csrf().disable(); }
}`
This configuration allows anyone to access the /oauth2/, /login/, and /logout/** endpoints. All other endpoints require authentication. When a user logs in via OAuth 2.0, they will be redirected to the /home endpoint. When they log out, they will be redirected to the / endpoint.
Generate a Token
To generate a token, you can use the JwtBuilder class from the spring-security-oauth2-jose dependency. Here's an example:
`import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtBuilder;
import org.springframework.security.oauth2.jwt.Jwts;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Date;
public class TokenGenerator {
public static void main(String[] args) throws NoSuchAlgorithmException { // Generate a key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Build the JWT JwtBuilder jwtBuilder = Jwts.builder() .setIssuer("https://example.com") .setAudience("https://example.com/resources") .setId("123") .setSubject("user@example.com") .setExpiration(Date.from(Instant.now().plusSeconds(3600))) .setIssuedAt(new Date()) .signWith(new NimbusJwtEncoder(keyPair.getPrivate())); Jwt jwt = jwtBuilder.build(); System.out.println(jwt.getTokenValue()); }
}`
This code generates a key pair, builds a JWT with the necessary claims, and signs it with the private key. The resulting token is printed to the console.
Note that this is just an example of how to generate a token. In practice, you would want to store the private key securely and use a different method of generating the expiration time.
Configure OAuth 2.0 Client
To use OAuth 2.0 in your application, you’ll need to configure a client. In Spring Boot, you can do this by adding properties to your application.properties file. Here's an example:
spring.security.oauth2.client.registration.example.client-id=client-id
spring.security.oauth2.client.registration.example.client-secret=client-secret
spring.security.oauth2.client.registration.example.scope=read,write
spring.security.oauth2.client.registration.example.redirect-uri=http://localhost:8080/login/oauth2/code/example
spring.security.oauth2.client.provider.example.authorization-uri=https://example.com/oauth2/authorize
spring.security.oauth2.client.provider.example.token-uri=https://example.com/oauth2/token
spring.security.oauth2.client.provider.example.user-info-uri=https://example.com/userinfo
spring.security.oauth2.client.provider.example.user-name-attribute=name
This configuration sets up an OAuth 2.0 client with the client ID and client secret provided by the example registration. It also sets the desired scope, redirect URI, and authorization, token, and user info URIs for the provider. Finally, it specifies that the user's name should be retrieved from the name attribute in the user info response.
Use the Token
Once you have a token, you can use it to access protected resources. For example, you can make an authenticated request to a resource server using the RestTemplate class. Here's an example:
`import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class ResourceClient {
public static void main(String[] args) { // Create a RestTemplate RestTemplate restTemplate = new RestTemplate(); // Set the authorization header HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth("token"); // Make the request HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange( "https://example.com/resource", HttpMethod.GET, entity, String.class ); // Print the response body System.out.println(response.getBody()); }
}`
This code sets the authorization header to the JWT token and makes a GET request to the /resource endpoint on the resource server. The response body is printed to the console.
Protect Endpoints
To protect endpoints in your Spring Boot application, you can use annotations provided by Spring Security. For example, you can use the @PreAuthorize annotation to ensure that a user has a specific role before they can access an endpoint. Here's an example:
`import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/admin") @PreAuthorize("hasRole('ADMIN')") public String adminEndpoint() { return "Hello, admin!"; }
}`
This code defines a controller with an endpoint that requires the user to have the ADMIN role in order to access it. If the user does not have the required role, they will receive a 403 Forbidden error.
Test the OAuth 2.0 flow
Start the application First, start the Spring Boot application that you’ve configured to use OAuth 2.0. You can do this by running the main() method in your application's main class.
Navigate to the login endpoint Next, navigate to the /login endpoint in your browser. For example, if your application is running on localhost:8080, you would go to http://localhost:8080/login.
Authenticate with the authorization server When you navigate to the login endpoint, your application will redirect you to the authorization server to authenticate. Depending on the authorization server, you may be prompted to enter your username and password, or you may be presented with a login button to authenticate with a third-party provider (such as Google or Facebook).
Grant access After you authenticate, you will be prompted to grant access to the scopes requested by the client. For example, if the client requested the read and write scopes, you may be prompted to grant access to read and write the user's data.
Receive the token Once you grant access, you will be redirected back to your application with an OAuth 2.0 token. This token can then be used to access protected resources.
For example, if you protected an endpoint with the @PreAuthorize annotation as described in the previous example, you could navigate to that endpoint and test whether or not you have access. If you have the required role, you will see the response from the endpoint. If you do not have the required role, you will receive a 403 Forbidden error.
以上是OAuth Spring Boot的详细内容。更多信息请关注PHP中文网其他相关文章!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多态性、Lambda表达式、StreamsAPI、泛型和异常处理。1.多态性让不同类的对象可以作为共同基类的对象使用。2.Lambda表达式使代码更简洁,特别适合处理集合和流。3.StreamsAPI高效处理大数据集,支持声明式操作。4.泛型提供类型安全和重用性,编译时捕获类型错误。5.异常处理帮助优雅处理错误,编写可靠软件。

java'stopfeatureSnificallyEnhanceItsperFormanCeanDscalability.1)对象 - 方向 - incipleslike-polymormormormormormormormormormormormormorableablefleandibleandscalablecode.2)garbageCollectionAutoctionAutoctionAutoctionAutoctionAutoctionautomorymanatesmemorymanateMmanateMmanateMmanagementButCancausElatenceiss.3)

JVM的核心组件包括ClassLoader、RuntimeDataArea和ExecutionEngine。1)ClassLoader负责加载、链接和初始化类和接口。2)RuntimeDataArea包含MethodArea、Heap、Stack、PCRegister和NativeMethodStacks。3)ExecutionEngine由Interpreter、JITCompiler和GarbageCollector组成,负责bytecode的执行和优化。

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

javaoffersseveralkeyfeaturesthatenhancecodingskills:1)对象 - 方向 - 方向上的贝利奥洛夫夫人 - 启动worldentities

thejvmisacrucialcomponentthatrunsjavacodebytranslatingitolachine特定建筑,影响性能,安全性和便携性。1)theclassloaderloader,links andinitializesClasses.2)executionEccutionEngineExecutionEngineExecutionEngineExecuteByteCuteByteCuteByteCuteBytecuteBytecuteByteCuteByteCuteByteCuteBytecuteByteCodeNinstRonctientions.3)Memo.3)Memo


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能