[英]Spring boot JWT cannot authorized rest api
我正在嘗試在我的Spring Boot 2項目上實現JWT。
我的參考鏈接https://www.callicoder.com/spring-boot-spring-security-jwt-mysql-react-app-part-2/
我的Securityconfig文件是
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
prePostEnabled=true,
jsr250Enabled = true,
securedEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private Environment env;
@Autowired
private UserSecurityService userSecurityService;
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
private BCryptPasswordEncoder passwordEncoder() {
return SecurityUtils.passwordEncoder();
}
@Autowired
private SecurityHandler securityHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
/* antMatchers("/**").*/
.antMatchers(PUBLIC_MATCHERS).
permitAll().anyRequest().authenticated();
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js","/login",
"/api/auth/signin")
.permitAll()
.antMatchers("/api/auth/**")
.permitAll()
.antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
.permitAll()
.anyRequest()
.authenticated();
// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
}
@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(WebSecurity web) throws Exception{
web.ignoring()
.antMatchers("/api/updateCardStatus","/api/login","*/uploads/***","/api/getUsersDetail","/api/getStudentDetails","/api/getAccountLoad","/api/issueDirectives","/api/changePassword","/api/cardActivation","/api/CustomerAccountCardDetails","/api/accountLoad","/api/updateConsumersProfile","/api/verifyCvv"
,"/api/updatePrepaidCardStatus","/api/getStatementData");
}
}
我的用戶班
@Entity
public class User {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id", nullable = false, updatable = false)
private Long id;
private String username;
private String password;
private String userType;
private boolean enabled=true;
@OneToOne(mappedBy = "user")
private BankUserDetails bankUserDetails;
@OneToOne(mappedBy = "user")
private SctUserDetails sctUserDetails;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonIgnore
private List<UserRole> userRoles = new ArrayList<>();
}
UserRole.java
@Entity
@Table(name="user_role")
public class UserRole {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long userRoleId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="user_id")
private User user;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="role_id")
private Role role;
}
角色.java
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int roleId;
private String name;
@OneToMany(mappedBy = "role", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private List<UserRole> userRoles = new ArrayList<>();
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(List<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
UserPrincipal.java
public class UserPrincipal implements UserDetails {
private Long id;
private String username;
private String password;
private String userType;
private boolean enabled=true;
@JsonIgnore
private static List<UserRole> userRoles = new ArrayList<>();
private Collection<? extends GrantedAuthority> authorities;
public UserPrincipal(Long id, String username, String password, Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.password = password;
this.authorities = authorities;
}
public static UserPrincipal create(User user) {
/* List<GrantedAuthority> authorities = user.getRoles().stream().map(role ->
new SimpleGrantedAuthority(role.getName().name())
).collect(Collectors.toList());*/
List<GrantedAuthority> authorites = new ArrayList<>();
userRoles.forEach(ur -> authorites.add(new Authority(ur.getRole().getName())));
return new UserPrincipal(
user.getId(),
user.getUsername(),
user.getPassword(),
authorites
);
}
public Long getId() {
return id;
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserPrincipal that = (UserPrincipal) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
現在,當我嘗試從郵遞員致電http://localhost:5060/token/generate-token
,我得到了響應
{
"timestamp": "2018-09-05T09:15:09.797+0000",
"status": 401,
"error": "Unauthorized",
"message": "Sorry, You're not authorized to access this resource.",
"path": "/token/generate-token"
}
現在我認為這是因為我無法獲得所需的權威。
由於我的實體與示例中給出的實體不同,我想我無法獲取經過完全認證的用戶對象。 我可能是錯的,但是有人可以幫助我指出確切的問題嗎?
您必須執行三個主要步驟來測試此樣本。 首先,您必須在角色表中插入一些角色。 之后,您必須向該應用程序注冊用戶。 最后,您可以登錄了。
此消息表示您沒有注冊該用戶。
該示例非常復雜,因為同時存在一些不同的事物,您可以在以下URL中找到有關此示例的簡單示例:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.