集成spring security

依赖

		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>

配置类

package com.ljh.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author lijiahao
 * @date 2022/2/7 12:49
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/code11","/doLogin")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((httpServletRequest, httpServletResponse, e) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httpServletResponse.getWriter().println("必须认证后才能访问");
                })
                .and()
                .logout()
                .and()
                .csrf()
                .disable();
    }


    @Override
    @Bean
    public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin").build());
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public KpatchaFilter kpatchaFilter() throws Exception {
        KpatchaFilter kpatchaFilter = new KpatchaFilter();
        kpatchaFilter.setFilterProcessesUrl("/doLogin");
        kpatchaFilter.setUsernameParameter("username");
        kpatchaFilter.setPasswordParameter("pwd");
        kpatchaFilter.setAuthenticationManager(authenticationManagerBean());
        kpatchaFilter.setAuthenticationSuccessHandler((req,response,authentication)->{
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg","登陆成功");
            result.put("用户信息",authentication.getPrincipal());
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.OK.value());
            String s = new ObjectMapper().writeValueAsString(result);
            response.getWriter().println(s);
        });
        kpatchaFilter.setAuthenticationFailureHandler((req,response,exception)->{
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg","登陆失败");
            result.put("失败原因",exception.getMessage());
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            String s = new ObjectMapper().writeValueAsString(result);
            response.getWriter().println(s);
        });
        return kpatchaFilter;
    }
}

自定义过滤器

package com.ljh.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author lijiahao
 * @date 2022/2/7 15:10
 */

public class KpatchaFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if ( !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        //获取请求验证码
        try {
            Map<String,String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            String username = map.get("username");
            String password = map.get("pwd");
            String kaptcha = map.get("code");
            //获取session中的验证码
            String code = (String) request.getSession().getAttribute("kaptcha");
            System.out.println("=============session中的验证码"+code);
            //获取用户名和密码认证
            if (!ObjectUtils.isEmpty(kaptcha)&&!ObjectUtils.isEmpty(code)&&kaptcha.equalsIgnoreCase(code)){
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
                setDetails(request,usernamePasswordAuthenticationToken);
                return this.getAuthenticationManager().authenticate(usernamePasswordAuthenticationToken);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new RuntimeException("验证码不匹配");
    }
}

你可能感兴趣的:(springboot,spring,java,安全)