SpringBoot Security front and back end separation login verification

SpringBoot Security front and back end separation login verification

This article is reproduced. Very well written, easy to understand

 

Recently, I have been researching the use of OAuth2, thinking about the whole single sign-on, I found many demos from the Internet but failed to implement it, maybe because I don’t understand the principle of OAuth2 at all. For a few days, I was getting more and more clueless, and I couldn’t give up. I turned my head and thought, OAuth2 is an extension on the basis of Security, and I don’t know anything about Security, so let’s study Security first. Build up Security and find out how it feels.

Just do it, and use Security in the ready-made SpringBoot 2.1.4.RELEASE environment.
Not to mention the use of simple security. The current project is separated from the front and back ends. The data format returned after successful login or failure must be in JSON format. It also needs to return a prompt message in JSON format when not logged in. It also needs to return JSON when logging out. formatted data. Regardless of the authorization, first return the data in JSON format. This one is done. I have also studied it for several days and read a lot of other people's experience. Research it.

Below, the code:

The first step is to introduce the Security configuration file in pom.xml

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

The second step is to increase the Configuration configuration file

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 参考网址:
 * https://blog.csdn.net/XlxfyzsFdblj/article/details/82083443
 * https://blog.csdn.net/lizc_lizc/article/details/84059004
 * https://blog.csdn.net/XlxfyzsFdblj/article/details/82084183
 * https://blog.csdn.net/weixin_36451151/article/details/83868891
 * 查找了很多文件,有用的还有有的,感谢他们的辛勤付出
 * Security配置文件,项目启动时就加载了
 * @author 程就人生
 *
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {      
    
    @Autowired
    private MyPasswordEncoder myPasswordEncoder;
    
    @Autowired
    private UserDetailsService myCustomUserService;
    
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
        http
        .authenticationProvider(authenticationProvider())
        .httpBasic()
        //未登录时,进行json格式的提示,很喜欢这种写法,不用单独写一个又一个的类
            .authenticationEntryPoint((request,response,authException) -> {
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                PrintWriter out = response.getWriter();
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("code",403);
                map.put("message","未登录");
                out.write(objectMapper.writeValueAsString(map));
                out.flush();
                out.close();
            })
            
            .and()
            .authorizeRequests()
            .anyRequest().authenticated() //必须授权才能范围
            
            .and()
            .formLogin() //使用自带的登录
            .permitAll()
            //登录失败,返回json
            .failureHandler((request,response,ex) -> {
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                PrintWriter out = response.getWriter();
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("code",401);
                if (ex instanceof UsernameNotFoundException || ex instanceof BadCredentialsException) {
                    map.put("message","用户名或密码错误");
                } else if (ex instanceof DisabledException) {
                    map.put("message","账户被禁用");
                } else {
                    map.put("message","登录失败!");
                }
                out.write(objectMapper.writeValueAsString(map));
                out.flush();
                out.close();
            })
            //登录成功,返回json
            .successHandler((request,response,authentication) -> {
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("code",200);
                map.put("message","登录成功");
                map.put("data",authentication);
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write(objectMapper.writeValueAsString(map));
                out.flush();
                out.close();
            })
            .and()
            .exceptionHandling()
            //没有权限,返回json
            .accessDeniedHandler((request,response,ex) -> {
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                PrintWriter out = response.getWriter();
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("code",403);
                map.put("message", "权限不足");
                out.write(objectMapper.writeValueAsString(map));
                out.flush();
                out.close();
            })
            .and()
            .logout()
            //退出成功,返回json
            .logoutSuccessHandler((request,response,authentication) -> {
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("code",200);
                map.put("message","退出成功");
                map.put("data",authentication);
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write(objectMapper.writeValueAsString(map));
                out.flush();
                out.close();
            })
            .permitAll();
            //开启跨域访问
            http.cors().disable();
            //开启模拟请求,比如API POST测试工具的测试,不开启时,API POST为报403错误
            http.csrf().disable();
    }
    
    @Override
    public void configure(WebSecurity web) {
        //对于在header里面增加token等类似情况,放行所有OPTIONS请求。
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        //对默认的UserDetailsService进行覆盖
        authenticationProvider.setUserDetailsService(myCustomUserService);
        authenticationProvider.setPasswordEncoder(myPasswordEncoder);
        return authenticationProvider;
    }
    
}

The third step is to implement the UserDetailsService interface

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
/**
 * 登录专用类
 * 自定义类,实现了UserDetailsService接口,用户登录时调用的第一类
 * @author 程就人生
 *
 */
@Component
public class MyCustomUserService implements UserDetailsService {

    /**
     * 登陆验证时,通过username获取用户的所有权限信息
     * 并返回UserDetails放到spring的全局缓存SecurityContextHolder中,以供授权器使用
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //在这里可以自己调用数据库,对username进行查询,看看在数据库中是否存在
        MyUserDetails myUserDetail = new MyUserDetails();
        myUserDetail.setUsername(username);
        myUserDetail.setPassword("123456");
        return myUserDetail;
    }
}

Description: This class is mainly used to receive the username passed by the login, and then it can be extended here to query whether the username exists in the database. If it does not exist, an exception can be thrown. For the sake of demonstration, this test writes the data to death.

The fourth step is to implement the PasswordEncoder interface

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
/**
 * 自定义的密码加密方法,实现了PasswordEncoder接口
 * @author 程就人生
 *
 */
@Component
public class MyPasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence charSequence) {
        //加密方法可以根据自己的需要修改
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return encode(charSequence).equals(s);
    }
}

Description: This class is mainly used to process password encryption and compare the password passed by the user with the database password (the password in UserDetailsService).

The fifth step is to implement the UserDetails interface

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * 实现了UserDetails接口,只留必需的属性,也可添加自己需要的属性
 * @author 程就人生
 *
 */
@Component
public class MyUserDetails implements UserDetails {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    //登录用户名
    private String username;
    //登录密码
    private String password;

    private Collection<? extends GrantedAuthority> authorities;

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
        this.authorities = authorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Description: This class is used to store user data after successful login. After successful login, you can use the following code to obtain:

MyUserDetails myUserDetails= (MyUserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();

After the code is written, you need to test it next. Only after the test can you prove the validity of the code. Let's use a browser first.

The first test is to visit the index before logging in, the page is directly redirected to the default login page, and the test interface is OK.

figure 1

In the second step of the test, after logging in, the json data is returned, and the test result is OK.

figure 2

The third step is to test, access the index, return the output login data, and the test result is OK.

image 3

The fourth step is to access logout, return json data, and test the interface OK.

Figure 4

The fifth step is to test with API POST, use this tool to simulate ajax request, and see the result of the request. First, visit the index, which can only be accessed after logging in. The test result is ok, and the JSON format data we need is returned.

Figure 5

The sixth step, in the login simulation dialog box, set the environment variable to keep the login status.

Figure 6

**Step 7, login test, returns data in JSON format, and the test result is OK.

 

Figure-7

The eighth step is to return to the index test window, send a request, and return the information of the current user in JSON format, and the test result is OK.

Figure-8

Step 9: Exit the test, return data in JSON format, and the test result is OK

Figure-9

The tenth step, after exiting, visit the index again, there is a problem, the login information is still there, LOOK!

Figure-10

 

Remove the tick in front of the header, that is, remove the cookie. It is normal at this time. The reason is very simple. When exiting, the cookie is not cleared. This can only be tested in a formal environment. No matter how simulated API POST is, it is still different from the formal environment.

If a 403 error is reported in the API POST test, you need to add the configuration configuration file

//开启跨域访问
http.cors().disable();
//开启模拟请求,比如API POST测试工具的测试,不开启时,API POST为报403错误
http.csrf().disable();

 

Guess you like

Origin blog.csdn.net/zs319428/article/details/107089473