security安全验证登录

一,简单的Secuity登录验证

1.导入依赖
        <!-- security安全验证依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
2.查询数据库
package com.xxx.blog.service.impl;

import com.xxx.blog.entity.TUser;
import com.xxx.blog.mapper.TUserMapper;
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.Service;
import javax.annotation.Resource;

/**
 * @Author user
 * UserDetailsService的实现类 实现对账户的数据查询
 */
@Service
public class CustomUserServiceImpl implements UserDetailsService {
    @Resource
    TUserMapper tUserMapper;
    
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.loadUserByUserName(s);
        if (tUser == null){
            throw new UsernameNotFoundException("用户名不存在!");
        }
        return tUser;
    }
}
3.创建SecurityConfig
package com.xxx.blog.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxx.blog.entity.TUser;
import com.xxx.blog.service.impl.CustomUserServiceImpl;
import com.xxx.blog.utils.RespBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
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.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author user
 * spring security是一个基于spring aop 和servlet过滤器的安全框架
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    CustomUserServiceImpl customUserService;

    @Bean
    PasswordEncoder passwordEncoder(){
        //强制要求密码加密
        return new BCryptPasswordEncoder();
    }

    //要有一个configure方法吧hrService整进来
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        //将用户信息存入到
        auth.userDetailsService(customUserService);
    }


    @Override
    protected  void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //表示剩下的任何请求只要验证之后都可以访问
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                //登录的访问接口。localhost:端口号/doLogin
                .loginProcessingUrl("/doLogin")
                //如果没有登录的话直接访问/login报错
                .loginPage("/login")
                //登陆成功的处理(用于前后端分离时,直接返回json
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp,
                                                        Authentication authentication) throws IOException, ServletException {
                        //如果登录失败也返回一段json
                        resp.setContentType("application/json;charset=utf-8");
                        //这是往出写的
                        PrintWriter out = resp.getWriter();
                        //Authentication里存放的的是登录成功的用户信息登录成功的hr对象
                        TUser tUser = (TUser) authentication.getPrincipal();
                        //为了安全。这里返回给前端时将密码设置为null
                        tUser.setPassword(null);
                        RespBean ok = RespBean.ok("登录成功!", tUser);
                        //把字符写出去
                        out.write(new ObjectMapper().writeValueAsString(ok));
                        out.flush();
                        out.close();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp,
                                                        AuthenticationException exception) throws IOException, ServletException {

                        //如果登录失败也返回一段json
                        resp.setContentType("application/json;charset=utf-8");
                        //这是往出写的
                        PrintWriter out = resp.getWriter();
                        RespBean error = RespBean.error("登录失败!");
                        if (exception instanceof LockedException){
                            error.setMsg("账户被锁定,请联系管理员!");
                        }else if (exception instanceof CredentialsExpiredException){
                            error.setMsg("密码过期,请联系管理员!");
                        }else if (exception instanceof DisabledException){
                            error.setMsg("账户被禁用,请联系管理员!");
                        }else if (exception instanceof BadCredentialsException){
                            error.setMsg("用户名或者密码输入错误,请重新输入!");
                        }
                        out.write(new ObjectMapper().writeValueAsString(error));
                        out.flush();
                        out.close();
                    }
                })
                //permitALL()表示放开和登陆有关的接口,csrf是关闭csrf,以便我们在 postman类似的软件测试被系统给拦截了
                .permitAll()
                .and()
                .logout()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp,
                                                Authentication authentication) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        out.write(new ObjectMapper().writeValueAsString(RespBean.ok("注销成功!")));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .csrf()
                .disable();
    }
}

4,设置没有登录的提示接口
package com.xxx.blog.controller;

import com.xxx.blog.utils.RespBean;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author user
 */
@RestController
@Slf4j
@ApiOperation("登录失败时会跳转")
public class LoginController {

    @RequestMapping("/login")
    public RespBean login(){
        return RespBean.error("尚未登陆,请先登录!");
    }
}
5.返回类
package com.xxx.blog.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author user
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RespBean {
    private Integer status;
    private String msg;
    private Object obj;


    public static RespBean build() {
        return new RespBean();
    }

    public static RespBean ok(String msg){
        return new RespBean(200,msg,null);
    }

    public static RespBean ok(String msg,Object obj){
        return new RespBean(200,msg,obj);
    }

    public static RespBean error(String msg){
        return new RespBean(500,msg,null);
    }

    public static RespBean error(String msg,Object obj){
        return new RespBean(500,msg,obj);
    }
}

番外

也可以单独处理登录后的返回处理,例如

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    MyUserDetailsService myDetailService;
    
    @Autowired
    private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource;
    
    protected Log log = LogFactory.getLog(this.getClass());
    
    @Autowired
    private AuthenticationProvider authenticationProvider; 

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        
        auth.authenticationProvider(authenticationProvider);
    }
    
    //定义登陆成功返回信息
    private class AjaxAuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            
            //User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            log.info("商户[" + SecurityContextHolder.getContext().getAuthentication().getPrincipal() +"]登陆成功!");
            //登陆成功后移除session中验证码信息
            request.getSession().removeAttribute("codeValue");
            request.getSession().removeAttribute("codeTime");
            
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write("{\"status\":\"ok\",\"msg\":\"登录成功\"}");
            out.flush();
            out.close();
        }
    }
    
    //定义登陆失败返回信息
    private class AjaxAuthFailHandler extends SimpleUrlAuthenticationFailureHandler {
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
            //登陆失败后移除session中验证码信息
            request.getSession().removeAttribute("codeValue");
            request.getSession().removeAttribute("codeTime");
            
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            PrintWriter out = response.getWriter();
            out.write("{\"status\":\"error\",\"msg\":\"请检查用户名、密码或验证码是否正确\"}");
            out.flush();
            out.close();
        }
    }
    
    //定义异常返回信息
    public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            response.sendError(HttpStatus.UNAUTHORIZED.value(),authException.getMessage());
        }

    }
    
    //定义登出成功返回信息
    private class AjaxLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler  {

        public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write("{\"status\":\"ok\",\"msg\":\"登出成功\"}");
            out.flush();
            out.close();
        }
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint())
        .and()
        .csrf().disable()
        .authorizeRequests()                   
            .antMatchers("/users/login_page","/users/captcha").permitAll()
            .anyRequest().authenticated()
            .and().formLogin().loginPage("/users/login_page")
                              .successHandler(new AjaxAuthSuccessHandler())
                              .failureHandler(new AjaxAuthFailHandler())
                              .loginProcessingUrl("/login")
                              .authenticationDetailsSource(authenticationDetailsSource)
            .and()
            .logout().logoutSuccessHandler(new AjaxLogoutSuccessHandler())
            .logoutUrl("/logout");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值