Explain the formlogin login authentication mode of spring security in detail

1、 Application scenario of formlogin

In the previous articles in this column, we have introduced the httpbasic mode of spring security. This mode is relatively simple. It only performs simple login verification through the header carrying HTTP, and there is no customized login page, so the use scenario is relatively narrow.

For a complete application system, the pages related to login verification are highly customized, very beautiful, and provide a variety of login methods. This requires spring security to support us to customize the login page, that is, the formlogin mode login authentication mode introduced in this article.

preparation

demand

The above is the preparation and requirements of formlogin mode introduced in this paper. Next, we will implement the core login verification logic. The preparation is very simple. Please implement it yourself. (create a new spring boot application. The login page, home page and four business pages can be written in very simple HTML without writing the actual business and style.)

2、 Explain

Three elements of formlogin mode:

Generally speaking, the login verification logic of business system using authority authentication framework is fixed, while resource access control rules and user information are loaded flexibly from database or other storage media. However, all the user, resource and permission information in this article are written in the code configuration. The purpose is to introduce the formlogin authentication mode and how to load the permission authentication related information from the database. I will also write an article in combination with the RBAC permission model.

3、 Implement basic configuration of formlogin mode

First, we will inherit the websecurityconfigureradapter and override the configure (httpsecurity HTTP) method, which is used to configure the login verification logic. Note the comments in the code below.

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable() //禁用跨站csrf攻击防御,后面的章节会专门讲解
      .formLogin()
        .loginPage("/login.html")//用户未登录时,访问任何资源都转跳到该路径,即登录页面
        .loginProcessingUrl("/login")//登录表单form中action的地址,也就是处理认证请求的路径
        .usernameParameter("uname")///登录表单form中用户名输入框input的name名,不修改的话默认是username
        .passwordParameter("pword")//form中密码输入框input的name名,不修改的话默认是password
        .defaultSuccessUrl("/index")//登录认证成功后默认转跳的路径
        .and()
      .authorizeRequests()
        .antMatchers("/login.html","/login").permitAll()//不需要通过登录验证就可以被访问的资源路径
        .antMatchers("/biz1").hasAnyAuthority("biz1") //前面是资源的访问路径、后面是资源的名称或者叫资源ID
        .antMatchers("/biz2").hasAnyAuthority("biz2")
        .antMatchers("/syslog").hasAnyAuthority("syslog")
        .antMatchers("/sysuser").hasAnyAuthority("sysuser")
        .anyRequest().authenticated();
  }
}

The above code is divided into two parts:

The first part is the formlogin configuration section, which is used to configure information related to login authentication logic. Such as: login page, login success page, login request processing path, etc.

The second part is the authorizerequests configuration side, which is used to configure the access rights of resources. For example, permitall of the development login page is open to access, and "/ biz1" (business page resource) can only be accessed by users with resource ID of "biz1".

At this time, when we visit a resource without access permission through the browser, we will jump to login HTML page.

4、 Requirements for implementing resource access restrictions

In the above, we have configured the permission rules for login authentication and resource access. We do not have a specific user. Let's configure a specific user. Override the configure (authenticationmanagerbuilder auth) method of the websecurityconfigureradapter

public void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.inMemoryAuthentication()
    .withUser("user").password(passwordEncoder().encode("123456")).authorities("biz1","biz2")
    .and()
    .passwordEncoder(passwordEncoder());//配置BCrypt加密
}
@Bean
public PasswordEncoder passwordEncoder(){
  return new BCryptPasswordEncoder();
}
inMemoryAuthentication指的是在内存里面存储用户的身份认证和授权信息。
withUser("user")用户名是user
password(passwordEncoder().encode("123456"))密码是加密之后的123456
authorities("biz1","biz2")指的是user用户拥有资源ID为biz1(业务一)和biz2(业务二)资源的权限

In this way, we realize the requirement that ordinary users can only access biz1 (service 1) and biz2 (service 2) resources. So the administrator user can access the configuration mode of all resources. Will you? The same formula, the same way, you can try it!

5、 Static resource access

In our actual development, the login page is login HTML and control layer controller login authentication '/ Login' must be unconditionally open. In addition, some static resources, such as CSS and JS files, usually do not need authentication permissions, and we need to open their access permissions. The following is the implementation method: override the configure (websecurity WEB) method of the websecurityconfigureradapter class

  @Override
  public void configure(WebSecurity web) {
    //将项目中静态资源路径开放出来
    web.ignoring().antMatchers("/config/**","/css/**","/fonts/**","/img/**","/js/**");
  }

summary

The above is the formlogin login authentication mode of spring Security introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support to our website! If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>