一直提示登录

来源:15-2 -后台编码-

jamko

2017-12-07

/**
 * Spring Security配置类
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//启用方法安全设置
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    private static final String KEY = "paisheng.top";

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();// 使用 BCrypt 加密
    }

    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder);// 设置密码加密方式
        return authenticationProvider;
    }

    /***
     * 自定义配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests().antMatchers("/css/**","/js/**","/fonts/**","/index").permitAll()// 都可以访问
                .antMatchers("/h2-console/**").permitAll()// 都可以访问
                .antMatchers("/admins/**").hasRole("ADMIN")// 需要相应的角色才能访问
                .and()
                .formLogin() //基于 Form 表单登录验证
                .loginPage("/login").failureUrl("/login-error")// 启用 remember me
                .and().rememberMe().key(KEY)// 启用 remember me
                .and().exceptionHandling().accessDeniedPage("/403");// 处理异常,拒绝访问就重定向到 403 页面
        http.csrf().ignoringAntMatchers("/h2-console/**"); // 禁用 H2 控制台的 CSRF 防护
        http.headers().frameOptions().sameOrigin();// 允许来自同一来源的H2 控制台的请求
    }

    /**
     *  认证信息管理
     * */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }
}

老卫老师,上面是我的权限配置类代码,我启动后,一直弹出登录提示框,我输入账号密码后也不对,请问这是什么原因?


写回答

2回答

jamko

提问者

2017-12-07

@Entity
public class TestUser implements UserDetails,Serializable{

    private static  final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增长策略
    private int id;

    @NotEmpty(message = "账号不能为空")
    @Size(min = 2,max = 20)
    @Column(nullable = false,length = 20,unique = true) // 映射为字段,值不能为空
    private String username;

    @NotEmpty(message = "真实姓名不能为空")
    @Size(min = 2,max = 20)
    @Column(nullable = false,length = 20)
    private String realname;

    @NotEmpty(message = "密码不能为空")
    @Size(min = 6,max = 200)
    @Column(nullable = false,length = 200)
    private String password;

    @NotEmpty(message = "电子邮箱不能为空")
    @Size(max = 50)
    @Email(message = "电子邮箱格式不对")
    @Column(nullable = false,length = 50,unique = true)
    private String email;

    @NotEmpty(message = "角色ID不能为空")
    @Column(nullable = false)
    private int authorityId;

    @NotEmpty(message = "部门ID不能为空")
    @Column(nullable = false)
    private int departmentId;

    @Column
    private int creater;

    @Column
    private Timestamp createtime;

    @Column
    private int mender;

    @Column
    private Timestamp modifytime;


    public int getId() {
        return id;
    }

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

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

    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAuthorityId() {
        return authorityId;
    }

    public void setAuthorityId(int authorityId) {
        this.authorityId = authorityId;
    }

    public int getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(int departmentId) {
        this.departmentId = departmentId;
    }

    public int getCreater() {
        return creater;
    }

    public void setCreater(int creater) {
        this.creater = creater;
    }

    public Timestamp getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Timestamp createtime) {
        this.createtime = createtime;
    }

    public int getMender() {
        return mender;
    }

    public void setMender(int mender) {
        this.mender = mender;
    }

    public Timestamp getModifytime() {
        return modifytime;
    }

    public void setModifytime(Timestamp modifytime) {
        this.modifytime = modifytime;
    }

    @ManyToMany(cascade = CascadeType.DETACH,fetch = FetchType.EAGER)
    @JoinTable(name = "user_authoriyt",joinColumns = @JoinColumn(name = "user_id",referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "authority_id",referencedColumnName = "id"))
    private List<Authority> authorities;

    public void setAuthorities(List<Authority> authorities) {
        this.authorities = authorities;
    }

    protected TestUser() {
    }

    public TestUser(String username, String realname, String password, String email, int authorityId, int departmentId) {
        this.username = username;
        this.realname = realname;
        this.password = password;
        this.email = email;
        this.authorityId = authorityId;
        this.departmentId = departmentId;
    }

    public TestUser(String username, String realname, String password, String email, int authorityId, int departmentId, int creater, Timestamp createtime, int mender, Timestamp modifytime) {
        this.username = username;
        this.realname = realname;
        this.password = password;
        this.email = email;
        this.authorityId = authorityId;
        this.departmentId = departmentId;
        this.creater = creater;
        this.createtime = createtime;
        this.mender = mender;
        this.modifytime = modifytime;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //需将List<Authority>转成List<SimpleGrantedAuthority>,否则前端拿不到角色列表名称
        List<SimpleGrantedAuthority> simpleAuthorities = new ArrayList<>();
        for(GrantedAuthority authority:this.authorities){
            simpleAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
        }
        return simpleAuthorities;
    }

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

    public void setEncodePassword(String password){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodePasswd = encoder.encode(password);
        this.password = encodePasswd;
    }

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

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

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

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

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

    @Override
    public String toString() {
        return String.format("User[id=%d, username='%s', realname='%s', email='%s', password='%s']", id, username, realname, email, password);
    }
}


这是用户的实体类代码


0
0

jamko

提问者

2017-12-07

//img.mukewang.com/szimg/5a2942d00001481415520792.jpg


上图是数据库TestUser表,和启动后的弹出框图。

我上午查过资料,也反复看了你blog-auth的代码,实在找不到原因,请老师帮忙看一下,谢谢!

0
1
老卫
那应该就是你的账号密码错,用课程初始化好的账号密码登录试下~
2017-12-07
共1条回复

基于Spring Boot技术栈博客系统企业级前后端实战

毕设 Elasticsearch搜索+Thymeleaf模板+JPA+Security+BootStrap

1296 学习 · 738 问题

查看课程