【问题标题】:postman showing 401 forbidden when testing spring security using email and pasword邮递员在使用电子邮件和密码测试 Spring Security 时显示 401 被禁止
【发布时间】:2020-06-27 16:29:28
【问题描述】:

我在 application.properties 中有休息端点配置:

spring.data.rest.base-path=/api/v1
security.user.name=admin
security.user.password=secret
security.user.role=USER,ADMIN

因为,我们在 pom.xml 中实现了 spring 安全性,我们得到了默认的登录屏幕,当我在那个框中输入用户名和密码时,我就获得了身份验证:

登录成功。但是,当我从邮递员那里尝试时,我得到了 401 unathorized on response:

我要检查的其余端点是:

@RestController
public class BasicAuthController {

    @GetMapping(path = "/basicauth")
    public AuthenticationBean basicauth() {
        System.out.println("hitted here");
        return new AuthenticationBean("You are authenticated");
    }
}

所以,我从邮递员那里尝试了相同的用户名和密码,并使用此 System.out.println("hitted here"); 在我的控制台上从邮递员发送时无法打印。

我在使用邮递员时收到 401 未经授权。甚至我的重发点 @GetMapping(path = "/basicauth") 也没有被调用。

我的网络安全配置是:

package in.ashwin.onlinebookstore.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private UserDetailsService customUserDetailsService;
 
 
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
         .userDetailsService(customUserDetailsService)
         .passwordEncoder(passwordEncoder());
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http         
         .headers()
          .frameOptions().sameOrigin()
          .and()
            .authorizeRequests()
             .antMatchers("/resources/**", "/webjars/**","/assets/**").permitAll()
                .antMatchers("/").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .httpBasic();
              
    }
 
}

Customuserdetailservice 是:

package in.ashwin.onlinebookstore.config;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import in.ashwin.onlinebookstore.entity.User;
import in.ashwin.onlinebookstore.repository.UserRepository;

@Service
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(userName)
       .orElseThrow(() -> new UsernameNotFoundException("Email " + userName + " not found"));
         return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(),
         getAuthorities(user));
    }

    private static Collection<? extends GrantedAuthority> getAuthorities(User user) {
        String[] userRoles = user.getRoles().stream().map((role) -> role.getName()).toArray(String[]::new);
        Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(userRoles);
        return authorities;
    }
}

AuthenticationBean.java

public class AuthenticationBean {

    private String message;

    public AuthenticationBean(String message) {
        this.message = message;
    }
}

我有基本的用户、角色和用户角色表。因为用户可以有很多角色。

我从邮递员发送时犯了什么错误?

【问题讨论】:

  • 需要配置 Spring Security WebSecurityConfig 类:.anyRequest().authenticated() .antMatchers("/api/auth/**").permitAll()
  • 你打算使用POST方法吗?
  • 哦,是的,谢谢,这是 get 方法,效果很好。

标签: java spring spring-boot


【解决方案1】:

您传递了错误的数据。

你需要将用户名和密码设置在邮递员基本身份验证中的application.properties中。

spring.security.user.name=admin
spring.security.user.password=secret

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 2013-07-11
    • 2015-11-14
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2012-08-19
    • 2021-07-28
    相关资源
    最近更新 更多