In the Part 1 of #SpringSecurity tutorial, I explained the difference between Authentication and Authorization. Now let's see how can we implement basic authentication in Spring.
Let's create a Spring Starter Project from STS, as of now this project has only Spring Web dependency.
Download the project from https://start.spring.io/, and import it in eclipse.
Create controller classes AuthenticationController.java and UserController.java inside it.
AutheticationController.java |
UserController.java |
Since we kept the controllers in 'com.greekykhs.controller' package, add the ComponentScan in Main class.
SpringSecurity21Application.java |
Once we run our Spring boot project, we can access below get rest webservices directly.
- http://localhost:8080/user/sayuser
- http://localhost:8080/user/echo/Hello!!
- http://localhost:8080/auth/sayhello
- http://localhost:8080/auth/echo/Michael
GIT URL: spring-security-21(tag 2)
Now let's say we don't want anyone to directly access these services, instead we want our users to enter user name and password. For this we need to make a small modification in pom.xml and add 'spring-boot-starter-security' dependency.
< dependency >
< groupId >org.springframework.boot< /groupId >
< artifactId >spring-boot-starter-security< /artifactId >
< /dependency >
Now, if you restart the spring boot project after adding this dependency and try to access any web-service you will get a prompt to enter user name and password ( form-based authentication), this is the default behavior for spring security.
The user name, by default is 'user' and we can get the password from the console for our application. When you check the console you will see a user-generated security password.
Let's say you do not want to use autogenerated password and username as 'user', in that case we can configure it via application.properties.
spring.security.user.name=greekykhs
spring.security.user.password=pass12345
When you add above two lines in the application.properties and restart the application, you won't see 'generated security password' on the console. And you can access the web-services with user name as 'greekykhs' and password as 'pass12345'.
No comments:
Post a Comment