ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

集成spring security

2022-02-08 09:05:47  阅读:116  来源: 互联网

标签:集成 spring kpatchaFilter springframework import org security new


依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </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("验证码不匹配");
    }
}

标签:集成,spring,kpatchaFilter,springframework,import,org,security,new
来源: https://blog.csdn.net/weixin_45386898/article/details/122817663

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有