1package com.howtodoinjava.demo.spring.config;
2
3import org.springframework.beans.factory.annotation.Autowired;
4import org.springframework.context.annotation.Bean;
5import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
6import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
8import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
10import org.springframework.security.crypto.password.PasswordEncoder;
11
12@EnableWebSecurity
13public class SecurityConfig extends WebSecurityConfigurerAdapter {
14
15 @Autowired
16 PasswordEncoder passwordEncoder;
17
18 @Override
19 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
20 auth.inMemoryAuthentication()
21 .passwordEncoder(passwordEncoder)
22 .withUser("user").password(passwordEncoder.encode("123456")).roles("USER")
23 .and()
24 .withUser("admin").password(passwordEncoder.encode("123456")).roles("USER", "ADMIN");
25 }
26
27 @Bean
28 public PasswordEncoder passwordEncoder() {
29 return new BCryptPasswordEncoder();
30 }
31
32 @Override
33 protected void configure(HttpSecurity http) throws Exception {
34 http.authorizeRequests()
35 .antMatchers("/login")
36 .permitAll()
37 .antMatchers("/**")
38 .hasAnyRole("ADMIN", "USER")
39 .and()
40 .formLogin()
41 .loginPage("/login")
42 .defaultSuccessUrl("/home")
43 .failureUrl("/login?error=true")
44 .permitAll()
45 .and()
46 .logout()
47 .logoutSuccessUrl("/login?logout=true")
48 .invalidateHttpSession(true)
49 .permitAll()
50 .and()
51 .csrf()
52 .disable();
53 }
54}
55
1<properties>
2 <failOnMissingWebXml>false</failOnMissingWebXml>
3 <spring.version>5.2.0.RELEASE</spring.version>
4</properties>
5
6<!-- Spring MVC Dependency -->
7<dependency>
8 <groupId>org.springframework</groupId>
9 <artifactId>spring-webmvc</artifactId>
10 <version>${spring.version}</version>
11</dependency>
12
13<!-- Spring Security Core -->
14<dependency>
15 <groupId>org.springframework.security</groupId>
16 <artifactId>spring-security-core</artifactId>
17 <version>${spring.version}</version>
18</dependency>
19
20<!-- Spring Security Config -->
21<dependency>
22 <groupId>org.springframework.security</groupId>
23 <artifactId>spring-security-config</artifactId>
24 <version>${spring.version}</version>
25</dependency>
26
27<!-- Spring Security Web -->
28<dependency>
29 <groupId>org.springframework.security</groupId>
30 <artifactId>spring-security-web</artifactId>
31 <version>${spring.version}</version>
32</dependency>
33