SpringBoot 401 Unauthorized问题

控制层接口代码:

@Api(tags = "控制图类型")
@RestController
@RequestMapping("/alarm/controlChart")
public class DimControlChartInfoController extends BaseController {
    @Resource
    private IDimControlChartInfoService dimControlChartInfoService;

    /**
     * 查询控制图类型列表
     */
    @ApiOperation("查询控制图类型列表")
    @PreAuthorize("@ss.hasPermi('alarm:controlChart:list')")
    @GetMapping("/list")
    public TableDataInfo list(DimControlChartInfo dimControlChartInfo) {
        startPage();
        List<DimControlChartInfo> list = dimControlChartInfoService.selectDimControlChartInfoList(dimControlChartInfo);
        return getDataTable(list);
    }

访问接口:

{
    "timestamp": "2023-02-22T10:12:59.231+08:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/alarm/controlChart/list"
}

定位找到问题存在如下情况:

1:导入了Spring-security包的问题
2Authorization 认证不通过,有些Authorization含有有效时长限制。(token时效问题)

Spring-security依赖包:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

当我们使用了Spring-security 之后,Spring Security默认对所有路径进行权限认证,并且提供默认的登陆页面。如果系统最终没有使用到Spring Security,将该依赖移除即可解决问题;如果系统确实需要使用Spring Security,那么可以自定义路径鉴权方式:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequest()              
            // 直接放行
            .antMatchers("/auth/**", "/error/**", "/dev/**").permitAll()
            // 权限认证
            .anyRequest().authenticated();
    }
}


Spring Security默认的configure(HttpSecurity httpSecurity)实际上等同于如下配置:

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequest()
            // 对所有http请求进行权限认证
            .anyRequest().authenticated().and()
            // 支持基于表单的登陆
            .formLogin().and()
            // 支持基于Basic方式的认证
            .httpBasic();
    }

你可能感兴趣的:(spring,boot,spring,boot,java,spring)