Spring Security (1) Custom form and authentication and authorization

1. Default form authentication

  Create a springboot project, dependent on:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

  Write a test controller

@RestController
@RequestMapping("/index")
public class IndexController {

    @RequestMapping("/test1")
    public String test1(String name, Integer age) {
        return "test1";
    }

}

  Start the project, visit http: // localhost: 8089 / BootDemo / index / test1, the default form authentication pops up

 

 

   The default user name is user, and the password is a random code generated dynamically and printed to the console. Of course, the username and password can be configured in application.properties

spring.security.user.name=test
spring.security.user.password=123

 

2. Custom form landing page

  Although the form landing page that comes with spring security can be started quickly and easily, most applications prefer to provide their own form landing page. In this case, a custom form landing page is required.

 

 

   WebSecurityConfig

package com.oy;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and().formLogin().loginPage("/mylogin.html" ) 
            .loginProcessingUrl ( "/ login") // Specify the path to process the login request. 
            permitAll () // The login page and "/ login" do not set permissions.and
             () .csrf (). disable ( ); 
    } 
}

  Form landing page

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>自定义表单登陆页</h2>
<form action="login" method="post">
用户名:<input type="text" name="username" /><br/>&nbsp;&nbsp;&nbsp;码:<input type="text" name="password" /><br/>
<input type="submit" value="提交" />
</form>
</body>
</html>
View Code

  Start the project, visit localhost: 8089 / BootDemo / index / test1, and automatically jump to the login page (the browser address is http: // localhost: 8089 / BootDemo / mylogin.html).

  Enter test / 123, login successfully, get the response result:

 

 

   If you enter the wrong username or password, the response result (status code 302, redirect to the login page)

 

 

   Corresponding to the project where the front end and the back end are separated, the redirect does not need to be done by the back end. The back end generally returns json data to inform the front end whether the login is successful or not. The front end decides how to handle the subsequent logic, rather than the server actively performing page jumps. This can also be achieved in Spring Security.

@EnableWebSecurity
 public  class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected  void configure (HttpSecurity http) throws Exception { 
        http.authorizeRequests (). AnyRequest (). Authenticated (). And () 
            .formLogin (). LoginPage ( "/mylogin.html" ) 
            .loginProcessingUrl ( "/ login") // Specify the path to process the login request
             // Specify the processing logic when the login is successful.successHandler 
            ( new AuthenticationSuccessHandler () { 

                @Override 
                public  void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                        Authentication authentication) throws IOException, ServletException {
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write("{\"code\":0, \"data\":{}}");
                }
                
            })
            // 指定登陆失败时的处理逻辑
            .failureHandler(new AuthenticationFailureHandler() {

                @Override
                public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                        AuthenticationException exception) throws IOException, ServletException {
                    response.setContentType("application/json;charset=utf-8");
                    response.setStatus(401);
                    response.getWriter().write("{\"code\":0, \"msg\":\"用户名或密码错误\"}");
                }
                
            })
            
            .permitAll().and()
            .csrf().disable();
    }
}

  Among them, the successHandler () method carries an Authentication parameter, carrying information such as the currently logged-in user name and its role; and the failureHandler () method carries an AuthenticationException exception parameter.

 

3. Authentication and authorization of custom database model

  The default security mechanism of Spring Security is followed: only one user, only one role. In actual development, this naturally cannot meet the requirements.

  Write three controllers for testing. Among them, the content under / admin / api is related to the background management of the system. You must have administrator rights (with the role of "admin") to access; / user / api must be logged in and have "user" ”Role to access.

@RestController
@RequestMapping("/admin/api")
public class AdminController {
    @GetMapping("/hello")
    public String hello() {
        return "hello, admin";
    }
}
@RestController
@RequestMapping("/user/api")
public class UserController {
    @GetMapping("/hello")
    public String hello() {
        return "hello, user";
    }
}
@RestController
@RequestMapping("/app/api")
public class AppController {
    @GetMapping("/hello")
    public String hello() {
        return "hello, app";
    }
}
View Code

  Start the project, visit http: // localhost: 8089 / BootDemo / user / api / hello, jump to the login page, and log in with test / 123. Visit http: // localhost: 8089 / BootDemo / user / api / hello again, and the server returns 403 at this time, indicating that the user authorization has failed (401 represents user authentication failure).

  Custom database model

  

 

 

 

 

 

 

 

 

 

 

---

 

Guess you like

Origin www.cnblogs.com/xy-ouyang/p/12695264.html