亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Spring Boot 不記名令牌認證給出 401

Spring Boot 不記名令牌認證給出 401

LEATH 2021-11-17 10:24:42
我是 Spring Boot 的新手,所以請幫助我。我已經讓它工作到我能夠生成一個Bearer Token未經身份驗證的請求的地步。接下來,我想將此令牌與端點一起使用,以便對我的請求進行身份驗證 - 這就是我遇到麻煩的地方。我總是收到 401,看起來我的配置有問題。這是我的代碼public class ApplicationUser {private String username;private String password;private String role;public ApplicationUser(String username, String password, String role) {    this.username = username;    this.password = password;    this.role = role;}public String getUsername() {    return username;}public String getPassword() {    return password;}public String getRole() {    return role;    }}JwtConfig 類:@Component("jwtConfig")public class JwtConfig {@Value("${security.jwt.uri:/auth/**}")private String Uri;@Value("${security.jwt.header:Authorization}")private String header;@Value("${security.jwt.prefix:Bearer }")private String prefix;@Value("${security.jwt.expiration:#{24*60*60}}")private int expiration;@Value("${security.jwt.secret:JwtSecretKey}")private String secret;public String getUri() {    return Uri;}public String getHeader() {    return header;}public String getPrefix() {    return prefix;}public int getExpiration() {    return expiration;}public String getSecret() {    return secret;}}
查看完整描述

3 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

根據您的要求,在您對多個路徑使用多個身份驗證之前,您真的不需要多個 http 安全配置(例如,對于某些路徑,您希望擁有 JWT,而對于某些路徑,您希望擁有基本身份驗證或 auth2)。


所以刪除SecurityCredentialsConfig并更新WebSecurity到下面,你會很好。


@Configuration

@EnableWebSecurity(debug = true)    // Enable security config. This annotation denotes config for spring security.

public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Autowired

    private JwtConfig jwtConfig;


    @Autowired

    private UserDetailsServiceImpl userDetailsService;


    @Override

    protected void configure(HttpSecurity http) throws Exception {

        http

                .csrf().disable()

                // make sure we use stateless session; session won't be used to store user's state.

                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                .and()

                // authorization requests config

                .authorizeRequests()

                // allow all who are accessing "auth" service

                .antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()

                // must be an admin if trying to access admin area (authentication is also required here)

                .antMatchers("/v1/cooks/**").hasAuthority("ADMIN")

                //for other uris

                //   .antMatchers(HttpMethod.GET, "/v1/**").hasRole("USER")

                // Any other request must be authenticated

                .anyRequest().authenticated()

                .and()

                // handle an authorized attempts

                .exceptionHandling().authenticationEntryPoint((req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED))

                .and()

                // Add a filter to validate the tokens with every request

                .addFilterAfter(new JwtTokenAuthenticationFilter(jwtConfig), UsernamePasswordAuthenticationFilter.class)

                .addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig));

    }


    @Override

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());

    }


    @Bean

    public BCryptPasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();

    }

}


查看完整回答
反對 回復 2021-11-17
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

嘗試添加這個

/**

在網絡安全類在線,

.antMatchers("/v1/cooks/**" ).access("hasRole('ADMIN')")

拜托,如果您能提供有關 Spring Boot 和安全依賴項的日志和版本,這對我們有很大幫助。


查看完整回答
反對 回復 2021-11-17
?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

  1. 嘗試從您的 CookAPI 中刪除 spring-boot-starter-security 依賴項。

  2. 正如我所見,zuul-server application.properties 中只添加了 auth-service。在cookAPI 屬性文件中為cookAPI 提供一個端口和應用程序名稱。將其添加到 zuul 屬性文件中。 zuul 屬性文件 我遵循了您提到的相同教程。


查看完整回答
反對 回復 2021-11-17
  • 3 回答
  • 0 關注
  • 240 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號