Spring Security(二) —— Guides

Abstract: Original Source  https://www.cnkirito.moe/spring-security-2/  "Xu" welcome to reprint reserved summary, thank you!



Previous article "Spring Security (a) -Architecture Overview", we introduced the Spring Security's infrastructure, this section guides us through an example given by the official Spring, Spring Security is to learn how to protect our applications, after a reading would be.

2 Spring Security Guides

2.1 introduces dependence

 1 <dependencies>
 2     <dependency>
 3         <groupId>org.springframework.boot</groupId>
 4         <artifactId>spring-boot-starter-web</artifactId>
 5     </dependency>
 6     <dependency>
 7         <groupId>org.springframework.boot</groupId>
 8         <artifactId>spring-boot-starter-security</artifactId>
 9     </dependency>
10     <dependency>
11         <groupId>org.springframework.boot</groupId>
12         <artifactId>spring-boot-starter-thymeleaf</artifactId>
13     </dependency>
14 </dependencies>

 

2.2 to create a free web application security restrictions because of our integrated springboot, so do not show the introduction of Spring Security document describes core, config rely only need to introduce springboot-starter-security can be.

This is a home, not subject to security restrictions

src/main/resources/templates/home.html

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
 3     <head>
 4         <title>Spring Security Example</title>
 5     </head>
 6     <body>
 7         <h1>Welcome!</h1>
 8 
 9         <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
10     </body>
11 </html>

 

src / main / resources / templates / hello.html contains a simple link on this page, jump to the "/ hello". Correspond to the following page

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
 3       xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
 4     <head>
 5         <title>Hello World!</title>
 6     </head>
 7     <body>
 8         <h1>Hello world!</h1>
 9     </body>
10 </html>

 

 1 @Configuration
 2 public class MvcConfig extends WebMvcConfigurerAdapter {
 3 
 4     @Override
 5     public void addViewControllers(ViewControllerRegistry registry) {
 6         registry.addViewController("/home").setViewName("home");
 7         registry.addViewController("/").setViewName("home");
 8         registry.addViewController("/hello").setViewName("hello");
 9         registry.addViewController("/login").setViewName("login");
10     }
11 
12 }

 

Spring Security 2.3 configuration next configuration of Spring MVC, allows us to access to the page.

A typical security configuration is as follows:

 1 @Configuration
 2 @EnableWebSecurity <1>
 3 public class WebSecurityConfig extends WebSecurityConfigurerAdapter { <1>
 4     @Override
 5     protected void configure(HttpSecurity http) throws Exception {
 6         http <2>
 7             .authorizeRequests()
 8                 .antMatchers("/", "/home").permitAll()
 9                 .anyRequest().authenticated()
10                 .and()
11             .formLogin()
12                 .loginPage("/login")
13                 .permitAll()
14                 .and()
15             .logout()
16                 .permitAll();
17     }
18 
19     @Autowired
20     public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
21         auth <3>
22             .inMemoryAuthentication()
23                 .withUser("admin").password("admin").roles("USER");
24     }
25 }

 

<2>  configure(HttpSecurity)defines which URL paths should be blocked, such as literally described: "/", "/ home " allow everyone to access, "/ login" as a log entry, also be allowed access, and the rest of the "/ hello before "you need to log in can access. <1> @EnableWebSecurity comment makes SpringMVC integrated web security support for the Spring Security. Further, WebSecurityConfig while incorporating the configuration class WebSecurityConfigurerAdapter, wherein the override a particular method for custom Spring Security configuration. Spring Security's entire workload, in fact, are concentrated in the configuration class, not just the guides, the actual project as well.

<3>  configureGlobal(AuthenticationManagerBuilder)configuration in memory and a user, admin / admin are the user name and password, the user has the USER role.

We currently have no login page, login page to create the following:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
 3       xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
 4     <head>
 5         <title>Spring Security Example </title>
 6     </head>
 7     <body>
 8         <div th:if="${param.error}">
 9             Invalid username and password.
10         </div>
11         <div th:if="${param.logout}">
12             You have been logged out.
13         </div>
14         <form th:action="@{/login}" method="post">
15             <div><label> User Name : <input type="text" name="username"/> </label></div>
16             <div><label> Password: <input type="password" name="password"/> </label></div>
17             <div><input type="submit" value="Sign In"/></div>
18         </form>
19     </body>
20 </html>

 

Finally, we add some content hello.html, for displaying user information. This Thymeleaf template provides a form for submitting a user name and password, which name = "username", name = "password" is the default form values ​​sent to "/ login". In the default configuration, Spring Security is provided to intercept the request and verifies a user's filter. If the authentication fails, the page will redirect to "/ login? Error", and displays the appropriate error message. When the user selects cancellation, the request will be sent to the "/ login? Logout".

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Sign Out"/>
        </form>
    </body>
</html>

 

Add 2.4 startup class after we are using Spring Security, HttpServletRequest # getRemoteUser () can be used to obtain a user name. Logout request will be sent to the "/ logout". After a successful logout, the user is redirected to the "/ login? Logout".

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws Throwable {
        SpringApplication.run(Application.class, args);
    }

}

 

Access Home http://localhost:8080/: 2.5 tests

home.htmlhome.html

Click here, try to access restricted pages: /helloSince not logged in, the result was also forced to jump to the login /login:

login.htmllogin.html

After entering the correct user name and password before jumping to want to visit /hello:

hello.htmlhello.html

Click Sign out Exit button, go to: /logoutreturn to the login page:

logout.htmllogout.html

 

Spring Security can not login, error: There is no PasswordEncoder mapped for the id "null"

Baidu online, I found that this is because the Spring security 5.0 added a variety of encryption methods, but also changed the format of a password.

 

To our project can also be a normal landing, you need to modify the code in configure. We want to pass over the front end of a certain way of password encryption, spring security official recommendation is to use bcrypt encryption. So how you do only need to specify it on the inside configure password encryption method.

After the modification is this:

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//inMemoryAuthentication 从内存中获取 
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user1").password(new BCryptPasswordEncoder().encode("123456")).roles("USER");
}


在inMemoryAuthentication()后面多了".passwordEncoder(new BCryptPasswordEncoder())",这相当于登陆时用BCrypt加密方式对用户密码进行处理。以前的".password("123456")" 变成了 ".password(new BCryptPasswordEncoder().encode("123456"))" ,这相当于对内存中的密码进行Bcrypt编码加密。比对时一致,说明密码正确,允许登陆。

如果你现在用的也是从内存中取密码,那么按照上面这么修改后应该会成功登录没有问题的。

If you are using a user name and password stored in the database, it is to want to use BCrypt encoding when the user registered user password is stored encrypted in the database. And modifying configure () method, was added ".passwordEncoder (new BCryptPasswordEncoder ())", to ensure that when the user logs on using bcrypt password and then processed in the database password comparison. as follows:

// injection userDetailsService implementation class 
auth.userDetailsService (that userService) .passwordEncoder ( new new BCryptPasswordEncoder ());

 

Guess you like

Origin www.cnblogs.com/lywJ/p/10984827.html