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

前后端不分离的springsecurity登录认证功能

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

前后端不分离的springsecurity登录认证功能

新建module

springsecurity03web

导入依赖(重点)
 
        
            org.springframework.boot
            spring-boot-starter-security
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.thymeleaf.extras
            thymeleaf-extras-springsecurity5
        

        
        
        
            com.alibaba
            druid-spring-boot-starter
            1.2.5
        
        
        
            mysql
            mysql-connector-java
            5.1.49
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.4
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.security
            spring-security-test
            test
        
    


配置yml
server:
    port: 8001


spring:
    datasource:
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
        river-class-name: com.mysql.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource


#    security:
#        user:
#            name: root
#            password: root

    #关闭thymeleaf缓存
    thymeleaf:
        cache: false

#Mybatis设置
mybatis:
    type-aliases-package: com.hb.entity
    mapper-locations: classpath*:mapper
//需要实现UserDetailService,需要返回一个UserDetail,为了能对应上所以实现UserDetail
public class User implements UserDetails {

    private Integer id;
    private String username;
    private String password;
    private Boolean enabled;//账户是否激活
    private Boolean accountNonExpired;//账户是否过期
    private Boolean accountNonLocked;//账户是否锁定
    private Boolean credentialsNonExpired;//密码是都过期
    private List role=new ArrayList<>();//关系属性,用来存储当前用户所有角色信息

    //返回权限信息
    @Override
    public Collection getAuthorities() {
        Set auth = new HashSet<>();
        role.forEach(role->{
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role.getName());
            auth.add(simpleGrantedAuthority);
        });
        return null;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

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

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

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

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

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public List getRole() {
        return role;
    }

    public void setRole(List role) {
        this.role = role;
    }
}

Role类

import lombok.Data;
//角色类
@Data
public class Role {
    private Integer id;
    private String name;
    private String nameZh;


}

DAO层
@Mapper
public interface UserDao {

    //根据用户名返回用户方法
    User loadUserByUserName(String username);

    //提供根据用户id查询用户角色信息方法
    List getRoleByUid(Integer id);
}

xml





    
        select id,
               username,
               password,
               enabled,
               accountNonExpired,
               accountNonLocked,
               credentialsNonExpired
        from user
        where username=#{username}
    
    

Service

重写loadUserByUsername方法

@Service
public class UserService implements UserDetailsService {

    @Autowired
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.loadUserByUserName(username);
        //查询用户
        if(ObjectUtils.isEmpty(user))throw new UsernameNotFoundException("用户名不正确");
        //查询权限信息
        List roleByUid = userDao.getRoleByUid(user.getId());
        user.setRole(roleByUid);
        return user;
    }
}
自定义security相关配置

编写mvc相关配置,这样我们就不需要在controller中写跳转登陆页面了

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
//页面跳转
public class MvcConfigure implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login.html").setViewName("login");
        registry.addViewController("/index.html").setViewName("index");
    }
}

编写SecurityConfigure配置类

  • configure(HttpSecurity http) 用来传UserService可以覆盖原有的
  • configure(AuthenticationManagerBuilder auth)自定义配置全局的AuthenticationManager
import com.hb.service.UserService;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;



@Configuration
public class SecurityConfigure extends WebSecurityConfigurerAdapter {


    //数据库实现
    @Autowired
    UserService userService;

    //全局AuthenticationManager
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        		//登陆页面login.html需要放行
                .mvcMatchers("/login.html").permitAll()
                //所有请求开启认证
                .anyRequest().authenticated()
                .and()
                //开启表单认证,就是上面一开始说的login页面
                .formLogin()
                //指定自定义登录页面,如果没有自定义的话就会跳转到springsecurity自己提供的
                .loginPage("/login.html")
                //指定登录的url
                .loginProcessingUrl("/dologin")
                //加个true,表示成功登录后总是跳转到这个页面
                .defaultSuccessUrl("/index.html",true)
                //失败后重定向到登录页面
                .failureUrl("/login.html")
                .and()
                .logout()//开启退出登录
                .logoutUrl("/logout")
                //退出成功后,跳转到login.html
                .logoutSuccessUrl("/login.html")
                .and()
                .csrf().disable();//关闭csrf

    }
}
结果


登陆成功

输入错误的密码

返回错误信息

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

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

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