Suppose you want to prevent unauthorized users to access the page then you have to put barrier to them by authorizing access. We can do this by using spring-security which provides basic authentication by securing all HTTP end points. For that you need to add spring-security dependency to your project, in maven we can add the dependency as:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Here's a security configuration that ensures that only authenticated users can access.
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource datasource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.csrf();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(datasource).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
Configuration | Description |
---|---|
@Configuration | Indicates that the class can be used by the Spring IoC container as a source of bean definitions. |
@Order (SecurityProperties.ACCESS_OVERRIDE_ORDER) | Override the access rules without changing any other autoconfigured features. Lower values have higher priority. |
WebSecurityConfigurerAdapter | The SecurityConfig class extends and overrides a couple of its methods to set some specifics of the security configuration. |
@Autowired of DataSource | Provide factory for connections to the physical data source. |
configure(HttpSecurity) | Overridden method defines which URL paths should be secured and which should not. |
.authorizeRequests().anyRequest() .fullyAuthenticated() | Indicates to spring that all request to our application requires to be authenticated. |
.formLogin() | Configures a form based login |
.loginPage("/login").failureUrl("/login?error").permitAll() | Specifies the location of the log in page and all users should be permitted to access the page. |
.logout().logoutUrl("/logout") .logoutSuccessUrl("/login?logout").permitAll() | The URL to redirect to after logout has occurred. The default is /login?logout. |
.csrf() | Used to prevent Cross Site Request Forgery, CSRF protection is enabled (default). |
configure(AuthenticationManagerBuilder){} | Overridden method to define how the users are authenticated. |
.jdbcAuthentication().dataSource(datasource) | Indicates to spring that we are using JDBC authentication |
.passwordEncoder(passwordEncoder()) | Indicates to spring that we are using a password encoder to encode our passwords. (A bean is created to return the choice of password Encoder, we are using BCrypt in this case) |
Notice that we have not configured any table name to be used or any query, this is because spring security by default looks for the below tables:
create table users (
username varchar(50) not null primary key,
password varchar(255) not null,
enabled boolean not null) ;
create table authorities (
username varchar(50) not null,
authority varchar(50) not null,
foreign key (username) references users (username),
unique index authorities_idx_1 (username, authority));
Insert the following rows into the above tables:
INSERT INTO authorities(username,authority)
VALUES ('user', 'ROLE_ADMIN');
INSERT INTO users(username,password,enabled)
VALUES('user', '$2a$10$JvqOtJaDys0yoXPX9w47YOqu9wZr/PkN1dJqjG9HHAzMyu9EV1R4m', '1');
The username in our case is user
and the password is also user
encrypted with BCrypt algorithm
Finally, Configure a datasource in the application.properties for spring boot to use:
spring.datasource.url = jdbc:mysql://localhost:3306/spring
spring.datasource.username = root
spring.datasource.password = Welcome123
Note:
Create and configure a login controller and map it to the path /login
and point your login page to this controller