springboot+mybatis+security ajax实现session保存User实体

2020-12-31 14:32:06 浏览数 (1)

AuthorityTeacher

代码语言:javascript复制
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

/**
 * @ProjectName: teaching
 * @Package: cn.bdqn.entity
 * @Author: huat
 * @Date: 2020/12/28 12:43
 * @Version: 1.0
 * 教师实体类
 */
public class AuthorityTeacher implements UserDetails {
    private int teacherId;
    private String username;//账号
    private String password;//密码
    private String teacherName;//真实名称
    private List<AuthorityRole> authorityRoles;

    public int getTeacherId() {
        return teacherId;
    }

    public void setTeacherId(int teacherId) {
        this.teacherId = teacherId;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    //@Override
    public String getPassword() {
        return password;
    }

    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }
    @Override
    public String getUsername() {
        return username;
    }

    public List<AuthorityRole> getAuthorityRoles() {
        return authorityRoles;
    }

    public void setAuthorityRoles(List<AuthorityRole> authorityRoles) {
        this.authorityRoles = authorityRoles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorityRoles;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Role

代码语言:javascript复制
import org.springframework.security.core.GrantedAuthority;

/**
 * @ProjectName: teaching
 * @Package: cn.bdqn.entity
 * @Author: huat
 * @Date: 2020/12/28 13:09
 * @Version: 1.0
 * 角色实体类
 */
public class AuthorityRole implements GrantedAuthority {
    private int roleId;
    private String roleName;//角色
    private String roleNameCN;//角色中文

    @Override
    public String getAuthority() {
        return roleName;
    }

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleNameCN() {
        return roleNameCN;
    }

    public void setRoleNameCN(String roleNameCN) {
        this.roleNameCN = roleNameCN;
    }
}

service

代码语言:javascript复制
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @ProjectName: teaching
 * @Package: cn.bdqn.service.admin
 * @Author: huat
 * @Date: 2020/12/28 16:23
 * @Version: 1.0
 */
public interface TeacherService extends UserDetailsService {


}
代码语言:javascript复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @ProjectName: teaching
 * @Package: cn.bdqn.service.admin
 * @Author: huat
 * @Date: 2020/12/28 16:24
 * @Version: 1.0
 */
@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherDao teacherDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return teacherDao.getAuthorityTeacherByUsername(username);
    }
}

权限配置类

代码语言:javascript复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * @ProjectName: teaching
 * @Package: cn.bdqn.filter
 * @Author: huat
 * @Date: 2020/12/28 12:24
 * @Version: 1.0
 */
@Configuration
@EnableWebSecurity
public class SpringSercurityConfig extends WebSecurityConfigurerAdapter  {

    @Autowired
    TeacherService teacherService;
    @Autowired
    AuthenticationSuccessHandler authenticationSuccessHandler;//ajax登陆成功使用
    @Autowired
    AuthenticationFailureHandler authenticationFailureHandler;//ajax登陆失败使用

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new MD5Util();
    }


    /**
     * 将账号密码设置在数据库当中
     * @param auth
     * @throws Exception
     */
    @Override
    public  void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                //将UserDetailsService放到容器中
                .userDetailsService(teacherService)
                //加密方式放入
                .passwordEncoder(passwordEncoder());
    }

    /**
     * 权限配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //释放静态资源,指定资源拦截规则,
        // 指定自定义认证页面,指定退出认证配置,csrf(跨域伪造请求)配置
        http.authorizeRequests()
                .antMatchers("intoLogin","login.jsp","/webapp/**").permitAll()//释放这些资源,允许匿名访问
                .antMatchers("/**").hasAnyRole("ADMIN","USER")
                .anyRequest().authenticated()//其他资源需要认证
                .and()
                .formLogin()
                .loginPage("/intoLogin")//登陆页请求的接口
                .loginProcessingUrl("/doLogin")//登陆地址,由springSecurity提供
                .usernameParameter("username")//登陆账号的name值
                .passwordParameter("password")
                .successHandler(authenticationSuccessHandler)//登陆成功
                .failureHandler(authenticationFailureHandler)//登陆失败
                .permitAll()//指定所有资源释放
                .and()
                .logout()//登出
                .logoutUrl("/logout")//指定登出路径
                .logoutSuccessUrl("/login.jsp")//登出成功后跳转的url
                .invalidateHttpSession(true)//是否清空session
                .permitAll()
                .and()
                .csrf()
                .disable();//关闭csrf(跨域伪造请求)
    }
}
代码语言:javascript复制
import com.alibaba.fastjson.JSON;
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.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: teaching
 * @Package: cn.bdqn.filter
 * @Author: huat
 * @Date: 2020/12/29 9:14
 * @Version: 1.0
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code",1);
        map.put("msg","账号密码错误");
        map.put("data","");
        /*   httpServletResponse.setContentType("application/json;charset=utf-8");*/
        PrintWriter out = httpServletResponse.getWriter();
        out.write(JSON.toJSONString(map));
        out.flush();
        out.close();
    }
}

登陆成功

代码语言:javascript复制
import com.alibaba.fastjson.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
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.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: teaching
 * @Package: cn.bdqn.filter
 * @Author: huat
 * @Date: 2020/12/29 9:16
 * @Version: 1.0
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(null!=auth){
            httpServletRequest.getSession().setAttribute("user",auth.getPrincipal());
        }
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("code",0);
        map.put("msg","登陆成功");
        map.put("data","");
        /*   httpServletResponse.setContentType("application/json;charset=utf-8");*/
        PrintWriter out = httpServletResponse.getWriter();
        out.write(JSON.toJSONString(map));
        out.flush();
        out.close();
    }
}

0 人点赞