簡體   English   中英

Spring 啟動安全 JDBC 基本認證失敗

[英]Spring Boot Security JDBC Basic Authentication Failure

我正在使用 Spring 啟動安全應用程序中的 PostgreSQL 數據庫設置 JDBC 身份驗證。

我為用戶和角色創建了下表,分別命名為“users”和“user_authorities”。

CREATE SEQUENCE users_id_seq
  INCREMENT 1
  START 1
  MINVALUE 1
  MAXVALUE 2147483647
  CACHE 1;

CREATE TABLE users (
  id       integer NOT NULL DEFAULT nextval('users_id_seq'),
  username VARCHAR ( 100 ) UNIQUE NOT NULL,
  password VARCHAR ( 100 ) NOT NULL,
  enabled  boolean NOT NULL,
  CONSTRAINT users_pkey PRIMARY KEY (id)
);

CREATE SEQUENCE user_authorities_id_seq
  INCREMENT 1
  START 1
  MINVALUE 1
  MAXVALUE 2147483647
  CACHE 1;

  CREATE TABLE user_authorities(
   id         integer NOT NULL DEFAULT nextval('user_authorities_id_seq'),
   user_id   integer NOT NULL,
   authority varchar(100) not null,
   CONSTRAINT user_authorities_pkey PRIMARY KEY (id)
  );

然后插入數據如下:

-- create user: 'user'
INSERT INTO users(username,password,enabled) 
VALUES('user','$2a$10$TfjwK4p4y2xn5f6RN78gwOz0Le.cMGuhNaz51WDjChGCDF9Z0yqci',true);

-- create user: 'admin'
INSERT INTO users(username,password,enabled) 
VALUES('admin','$2a$10$lbZgb/zt4jBoPjqF.RfsOOOKyKJMOZjFS8QMyO.5p7Ob/jzf7ASPC',true);

-- create role: 'USER' for the user: 'user'
INSERT INTO users_authorities(user_id,authority) VALUES((select u.id from users u where u.username = 
'user'),'USER');

-- create role: 'ADMIN' for the user: 'admin'
INSERT INTO user_authorities(user_id,authority) VALUES((select u.id from users u where u.username = 
'admin'),'ADMIN');

Spring 啟動應用程序端,我有安全配置:

package com.mi.rest.webservices.restfulwebservices.security;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import 
 org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

   @Autowired
   DataSource dataSource;

   @Autowired
   BCryptPasswordEncoder bCryptEncoder;

   private static final String GET_USERS_SQL = "SELECT username, password, enabled from users where       
   username = ?";

   private static final String GET_USER_AUTHORITIES_SQL = "SELECT u.username, a.authority FROM    
   user_authorities a, users u WHERE u.username = ? AND u.id = a.user_id";

/**
 * Specify authentication scheme:
 * 
 * 1. In memory
 * 2. JDBC
 * 3. LDAP
 * 
 */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    /**
     auth.inMemoryAuthentication()  
   .withUser("user").password("$2a$10$TfjwK4p4y2xn5f6RN78gwOz0Le.cMGuhNaz51WDjChGCDF9Z0yqci")
   .roles("USER")
   .and()
   .withUser("admin")
   .password("$2a$10$lbZgb/zt4jBoPjqF.RfsOOOKyKJMOZjFS8QMyO.5p7Ob/jzf7ASPC")
   .roles("ADMIN");
    */
    
    auth
    .jdbcAuthentication()       
    .usersByUsernameQuery(GET_USERS_SQL)
    .authoritiesByUsernameQuery(GET_USER_AUTHORITIES_SQL)
    .dataSource(dataSource)
    .passwordEncoder(bCryptEncoder);
}

//Authorization:
@Override
protected void configure(HttpSecurity http) throws Exception {

    http
            //HTTP Basic authentication
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/todo-app/userOnly").hasRole("USER")
            .antMatchers(HttpMethod.GET, "/todo-app/todos/**").hasRole("USER")
            .antMatchers(HttpMethod.GET, "/todo-app/adminOnly").hasRole("ADMIN")
            .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
            //.and()
            //.csrf().disable()
            ;
   }

 }

現在為了測試我的設置,我有一個帶有以下端點的 RestController:

  package com.mi.rest.webservices.restfulwebservices.controllers;

  import java.util.ArrayList;
  import java.util.Date;
  import java.util.List;

  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.jdbc.core.JdbcTemplate;
  import org.springframework.web.bind.annotation.CrossOrigin;
  import org.springframework.web.bind.annotation.GetMapping;
  import org.springframework.web.bind.annotation.PathVariable;
  import org.springframework.web.bind.annotation.PostMapping;
  import org.springframework.web.bind.annotation.RequestBody;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RestController;

  @RestController
  @RequestMapping("/todo-app")
  @CrossOrigin(origins = "http://localhost:4200")
  public class TodoController { 

      @GetMapping("/userOnly")
      public TodoItem getForUserOnly() {
       TodoItem todo9 = new TodoItem();
       todo9.setId(9);
       todo9.setDescription("USER role item");
       todo9.setDone(false);
       todo9.setTargetDate(new Date());
       todo9.setUser("user");
    
       return todo9;
   }

   @GetMapping("/adminOnly")
   public TodoItem getForAdminOnly() {
       TodoItem todo9 = new TodoItem();
       todo9.setId(9);
       todo9.setDescription("ADMIN role item");
       todo9.setDone(false);
       todo9.setTargetDate(new Date());
       todo9.setUser("admin");
    
       return todo9;
      }
  }

使用 Postman 進行測試,我不斷收到 403 禁止所有測試(使用用戶和管理員授權的端點)。

這張照片缺少什么? 非常感謝任何提示和建議。

不要說我將“角色”附加到每個權限。 Spring 希望當局有一個前綴"ROLE...."

參考 - Spring 文檔

編輯您的users_authorities表的插入

-- create role: 'USER' for the user: 'user'
INSERT INTO users_authorities(user_id,authority) VALUES((select u.id from users u where u.username = 
'user'),'ROLE_USER');

-- create role: 'ADMIN' for the user: 'admin'
INSERT INTO user_authorities(user_id,authority) VALUES((select u.id from users u where u.username = 
'admin'),'ROLE_ADMIN');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM