栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

集成spring security

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

集成spring security

依赖
		
            org.springframework.boot
            spring-boot-starter-security
        
配置类
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;


@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 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 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;



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 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("验证码不匹配");
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/732675.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号