Estou com problema mesmo colocando tudo corretamente, está dando o mesmo problema Show
"error": "unauthorized", "error_description": "Full authentication is required to access this resource"
import java.security.Principal; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableAuthorizationServer @EnableResourceServer @RestController public class AuthApplication {
} package br.com.alura.microservice.auth; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; public class AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {
} package br.com.alura.microservice.auth; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {
} ` In this tutorial, we’re gonna build a Spring Boot Application that supports Token based Authentication with JWT. You’ll know:
Lots of interesting things ahead, let’s explore together. – Related Posts:
– Using MongoDB: Spring Boot JWT Authentication with Spring Security and MongoDB – Fullstack:
Deployment:
Contents
Overview of Spring Boot JWT Authentication exampleWe will build a Spring Boot application in that:
This is our Spring Boot application demo running with MySQL database and test Rest Apis with Postman. These are APIs that we need to provide:
The database we will use could be PostgreSQL or MySQL depending on the way we configure project dependency & datasource. Spring Boot Signup & Login with JWT Authentication FlowThe diagram shows flow of how we implement User Registration, User Login and Authorization process. A legal JWT must be added to HTTP Authorization Header if Client accesses protected resources. You will need to implement Refresh Token: More details at: Spring Boot Refresh Token with JWT example You can also visit The example that uses HttpOnly Cookies instead. Spring Boot Server Architecture with Spring SecurityYou can have an overview of our Spring Boot Server with the diagram below: Now I will explain it briefly. Spring Security ( – – – – – – Repository contains Controller
receives and handles request after it was filtered by – – Understand the architecture deeply and grasp the overview more easier: Technology
Project StructureThis is folders & files structure for our Spring Boot application: security: we configure Spring Security & implement Security Objects here.
( controllers handle signup/login requests & authorized requests.
repository has intefaces that extend Spring Data JPA
models
defines two main models for Authentication (
payload defines classes for Request and Response objects We also have application.properties for configuring Spring Datasource, Spring Data JPA and App properties (such as JWT Secret string or Token expiration time). Setup new Spring Boot projectUse Spring web tool or your development tool (Spring Tool Suite, Eclipse, Intellij) to create a Spring Boot project. Then open pom.xml and add these dependencies:
We also need to add one more
dependency.
– or MySQL is your choice:
Configure Spring Datasource, JPA, App propertiesUnder src/main/resources folder, open application.properties, add some new lines. For PostgreSQL
For MySQL
Create the modelsWe’re gonna have 3 tables in database: users, roles and user_roles for many-to-many relationship. Let’s define these models.
Implement RepositoriesNow, each model above needs a repository for persisting and accessing data. In repository package, let’s create 2 repositories. UserRepository There are 3 necessary methods that
RoleRepository This repository also extends
Configure Spring SecurityIn security package, create WebSecurityConfig.java
Let me explain the code above. – – – We override the – Spring Security will load User details to perform authentication & authorization. So it has – The
implementation of – We also need a Implement UserDetails & UserDetailsServiceIf the authentication process is successful, we can get User’s information such as username, password, authorities from an
If we want to get more data (id, email…),
we can create an implementation of this security/services/UserDetailsImpl.java
Look at the code above, you can notice that we convert As I have said before, we need
So we implement it and override security/services/UserDetailsServiceImpl.java
In the code above, we get full custom User object using Filter the RequestsLet’s define a filter that executes once per request. So we create security/jwt/AuthTokenFilter.java
What we do inside After this, everytime you want to get
Create JWT Utility classThis class has 3 funtions:
security/jwt/JwtUtils.java
Remember that we’ve added Handle Authentication ExceptionNow we create security/jwt/AuthEntryPointJwt.java
We’ve already built all things for Spring Security. The next sections of this tutorial will show you how to implement Controllers for our RestAPIs. Define payloads for Spring RestControllerLet me summarize the payloads for our RestAPIs:
– Responses:
To keep the tutorial not so long, I don’t show these POJOs
here. Create Spring RestAPIs ControllersController for Authentication This controller provides APIs for register and login actions. –
–
controllers/AuthController.java
Controller for testing Authorization There are 4 APIs: Do you remember that we used
Now we can secure methods in our Apis with controllers/TestController.java
Run & TestRun Spring Boot application with command: Tables that we define in
models package will be automatically generated in Database.
We also need to add some rows into roles table before assigning any role to User.
Then check the tables:
Register some users with
Our tables after signup could look like this.
Access public resource: GET
Access protected resource: GET Login an account: POST
Access Access Access Solve Problem: javax.validation cannot be resolvedFor Spring Boot 2.3 and later, you can see the compile error: It is because Validation Starter no longer included in web starters. So you need to add the starter yourself.
– For Gradle:
Solve Problem with JDK 14If you run this Spring Boot App with JDK 14 and get following error when trying to authenticate:
Just add following dependency to pom.xml:
Everything’s gonna work fine. ConclusionCongratulation! Today we’ve learned so many interesting things about Spring Security and JWT Token based Authentication in just a Spring Boot example. For understanding the architecture deeply and grasp the overview more easier: You should continue to know how to implement Refresh Token: Or visit The example that uses HttpOnly Cookies instead. You can also know how to deploy Spring Boot App on AWS (for free) with this tutorial. Happy learning! See you again. Further Reading
Related Posts:
Deployment:
Fullstack CRUD App: If you need a
working front-end for this back-end, you can find Client App in the posts: Associations: Source CodeYou can find the complete source code for this tutorial on Github. |