gpt4 book ai didi

spring-boot - @Secured 注释不适用于方法授权

转载 作者:行者123 更新时间:2023-12-04 02:58:54 25 4
gpt4 key购买 nike

我的安全配置为:

    package com.vaidiksanatansewa.guruji.security;

import javax.sql.DataSource;

import com.vaidiksanatansewa.guruji.service.UserloginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;


@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, IF(status=1, true, false) as enabled from users where username=? and status=1 ")
.authoritiesByUsernameQuery("select users.username as username, user_role.role as role from users inner join user_role on users.role_fid=user_role.id where users.username=? and users.status=1");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and()
.authorizeRequests().antMatchers( "/appointment/**").permitAll()
.antMatchers("/user/**").hasAnyAuthority("ADMIN","USER")
.and()
.csrf().disable();
}


}

和方法在 Controller 中注释为:

....
@RequestMapping("/user")
@Secured("ROLE_ADMIN")
public List<UserAll> getAll() {

return userService.getAll();
}


@RequestMapping("/user/{id}")
@Secured("ROLE_USER")
public UserAll getById(@PathVariable Long id) {

return userService.getById(id);
}
......

在没有启用方法授权的情况下一切正常,但是当它被启用时我得到访问被拒绝的错误。似乎所需的一切都已设置,但仍然无法正常工作。你能帮我找出来吗??

最佳答案

感觉很奇怪,但是将 @Secured("ROLE_ADMIN") 替换为 @PreAuthorize("hasAuthority('ADMIN')") 就可以了。我也尝试过执行 @Secured("hasRole('ROLE_ADMIN')") 但这也没有用。嗯,至于现在已经解决了。

关于spring-boot - @Secured 注释不适用于方法授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com