scypreferhjh
2022-05-27 12:58
采纳率: 40%
浏览 51
已结题

springboot整合springSecurity,登录权限判定时,无法跳转

代码

SecurityConfig

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DBUserDetailsService dbUserDetailsService;

    //拦截
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("1");
        http.csrf().disable(); //关闭CSRF验证

        http.authorizeRequests()
                .antMatchers("/","/index","/login").permitAll()
                .antMatchers("/seat/**").hasAuthority("user")
                .antMatchers("/sigin/**").hasAuthority("user")
                .antMatchers("/reserve/**").hasAuthority("user")
                .antMatchers("/user/**").hasAuthority("user")
                .antMatchers("/admin/**").hasAuthority("admin") //访问admin下面的接口需要admin权限
                .and()
                .formLogin().loginPage("/");
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //添加自定义验证器
        auth.userDetailsService(dbUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
}

UserBean

@Component
public class UserBean implements UserDetails {
    private String userID;
    private String userName;
    private String password;
    private String realName;
    private String phoneNumber;
    private String email;
    private Integer gender;
    private String authoritiy; //权限
    private String signature;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        simpleGrantedAuthorities.add(new SimpleGrantedAuthority(authoritiy));

        return simpleGrantedAuthorities;
    }

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

    @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;
    }
}

DBUserDetailsService

@Service
public class DBUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userMapper.getUserByUsername(username);
 /* @Select("select * from user where userName = #{username}")
    UserBean getUserByUsername(@Param("username") String username);*/
    }
}

html中js验证登录

<script>

    layui.use(['layer'],function (){
        var layer = layui.layer, $ = layui.jquery;

        $("#login").on('click',function () {
            let username, password;
            username =$.trim($("#username").val());
            password =$.trim($("#password").val());

            $.ajax({
                type:"POST",
                url: "/login",
                async: true,
                dataType: "json",
                data:{"username":username, "password":password},
                success: function (result) {
                    if (result === "用户不能为空") {
                        layer.open({
                            title: '提示'
                            ,content: result.toString()
                            ,icon: 2
                            ,time:3000
                        });
                    } else if (result === "密码不能为空") {
                        layer.open({
                            title: '提示'
                            ,content: result.toString()
                            ,icon: 2
                            ,time:3000
                        });
                    } else if (result === "密码错误") {
                        layer.open({
                            title: '提示'
                            ,content: result.toString()
                            ,icon: 2
                            ,time:3000
                        });
                    } else if (result === "权限不够!") {
                        layer.open({
                            title: '提示'
                            ,content: result.toString()
                            ,icon: 7
                            ,time:3000
                        });
                    } else {
                        layer.open({
                            title: '提示'
                            ,content: result.toString()
                            ,icon: 1
                            ,yes: function (index) {
                                layer.close(index);
                                window.location.href = "/admin/toDashboard";
                            }
                        });
                    }
                }
            });
        });
    });

img

处理登录请求的Controller

@Controller
public class WebLoginController {

    @Autowired
    WebLoginService webLoginService;


    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        String message = webLoginService.Login(username, password);

        return JSONUtils.getJSON(message);
    }

}

对应的service

@Service
public class WebLoginService {

    @Autowired
    UserMapper userMapper;

    /**
     * 登录
     * @param userName
     * @param password
     * @return
     */
    public String Login(String userName, String password) {
        if (StringUtils.isEmpty(userName)) return "用户不能为空";
        if (StringUtils.isEmpty(password)) return "密码不能为空";

        User user = userMapper.getUserByUserName(userName);


        if (!password.equals(user.getPassword())) return "密码错误";

        if ("user".equals(user.getAuthoritiy())) {
            return "权限不够!";
        }

        //发送session
        StpUtil.login(userName);
        return "登陆成功!";
    }

}

数据库中信息

img

运行结果及报错内容
  1. 输入

img


2. 点击登录

img

我们能够看到,执行了

img


这一部分,但是当我点击yes时,页面只是刷新了一下

img


没有跳转

  1. 后台输出

img

从中可以看出,进入了configure(HttpSecurity http)方法

我的解答思路和尝试过的方法

我有思考过是否是WebMvcConfig.java的配置导致问题,

img


当我把他们内容都注释掉的时候,还是无用,我在思考是不是我数据库中是userName,而不是username的原因

我想要达到的结果

希望能够正常运行

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题