装入依赖

引入spring-sercurity

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

编写配置文件

package com.java1234.config;

import com.java1234.common.security.LoginFailedHandler;
import com.java1234.common.security.LoginSucessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * spring security配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoginSucessHandler loginSucessHandler;

    @Autowired
    private LoginFailedHandler loginFailedHandler;

    private static final String URL_WHITELIST[] = {"/login", "/logout", "/user/captcha", "/password", "/image/**", "/test/**"};

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启跨域 和 csrf攻击 关闭
        http
                .cors()
                .and()
                .csrf()
                .disable()
        // 登录配置
                .formLogin()
         .successHandler(loginSucessHandler)
         .failureHandler(loginFailedHandler)
        // .and()
        // .logout()
        // .logoutSuccessHandler()
        // session禁用配置
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        // 拦截规则配置
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .anyRequest().authenticated();
        // 异常处理器配置
        // 自定义过滤器配置
    }

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

登录成功逻辑实现

package com.java1234.common.security;

import com.alibaba.druid.support.json.JSONUtils;
import com.java1234.common.constant.MsgConstant;
import com.java1234.entity.R;
import com.java1234.utils.JwtUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utc-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        String username = "user";
        String token = JwtUtils.genJwtToken(username);
        outputStream.write(JSONUtils.toJSONString((R.ok(MsgConstant.LOGIN_SUCCESS).put("authorization",token))).getBytes());//将数据转换成json字符串写入到输出流中
        outputStream.flush();//发送数据到前端
        outputStream.close();
    }
}

登录失败逻辑

package com.java1234.common.security;

import com.alibaba.druid.support.json.JSONUtils;
import com.java1234.entity.R;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        OutputStream outputStream = httpServletResponse.getOutputStream();
        String message = e.getMessage();
        if(e instanceof BadCredentialsException) {
            message = "用户名或者密码错误";
        }
        outputStream.write(JSONUtils.toJSONString(R.error(message)).getBytes());
        outputStream.flush();
        outputStream.close();
    }
}

原文地址:http://www.cnblogs.com/guozhiqiang/p/16905342.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性