简体   繁体   English

spring boot/spring security中如何将用户添加到OAuth2 Auth服务器

[英]How to add users to OAuth2 Auth server in spring boot/spring security

I am building a reddit clone with Spring Boot and AngularJS. Currently I have a rest repository of posts and comments that can be accessed when a user logs in.我正在使用 Spring Boot 和 AngularJS 构建一个 reddit 克隆。目前我有一个 rest 的帖子和评论存储库,用户登录时可以访问这些存储库。

Security Config file安全配置文件

package com.example.MundaneHeroes.Configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;



@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception
    {
        http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/account/**").permitAll().anyRequest().authenticated().and().oauth2Login();

    }
}

application.yml file application.yml文件

server:
  port: 8082
  servlet:
    session:
      cookie:
        name: UISESSION
spring:
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    password:
    username: sa

  security:
    oauth2:
      client:
        registration:
          custom-client:
            client-id: R2dpxQ3vPrtfgF72
            client-secret: fDw7Mpkk5czHNuSRtmhGmAGL42CaxQB9
            client-name: Auth Server
            scope: user_info
            provider: custom-provider
            redirect-uri-template: http://localhost:8082/login/oauth2/code/
            client-authentication-method: basic
            authorization-grant-type: authorization_code
        provider:
          custom-provider:
            token-uri: http://localhost:8081/auth/oauth/token
            authorization-uri: http://localhost:8081/auth/oauth/authorize
            user-info-uri: http://localhost:8081/auth/user/me
            user-name-attribute: name

I mostly followed this tutorial here on creating an authorization server我主要是按照这里的教程创建授权服务器

tutorial 教程

My problem is I havent been able to add users to this authorization server我的问题是我无法将用户添加到此授权服务器

I added a User entity, and a JPA repository of users and added code to configure additional accept additional users beyond the 1 in the tutorial.我添加了一个用户实体和一个 JPA 用户存储库,并添加了代码来配置额外的接受教程中 1 之外的其他用户。 I've overriden user details, so I believe thats a good start.我已经覆盖了用户详细信息,所以我相信这是一个好的开始。


@Value("${user.oauth.user.username}")
    private String username;

    @Value("${user.oauth.user.password}")
    private String password;

    @Autowired
    private UserService userDetailsService;

    @Override
    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.inMemoryAuthentication().withUser(username).password(passwordEncoder().encode(password)).roles("ADMIN");
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
        //auth to userService and password encoder
    }

However I have no idea how to accept data from the /account/ page where the client would create a new account.但是我不知道如何从客户创建新帐户的 /account/ 页面接受数据。

here is the html code for account.html这是帐户的 html 代码。html

<!DOCTYPE html>
<html lang="en" ng-app="userApp">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular-route.js"></script>
    <script src="account.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <link rel="stylesheet" href="../app.css" />
</head>
<body ng-controller="UserController">

Username <input ng-model="username"/><br>
Password <input ng-model="password"/><br>
Email <input ng-model="email"/><br>
<input type="button" value="Send" ng-click="postuser(username, password, email)" />


<p>StatusCode: {{statusval}}</p>

<p>Status: {{status}}</p>

<p>Response {{headers}}</p>

</body>
</html>

and account.js和 account.js

'use strict';


var userApp = angular.module('userApp', []);

userApp.controller('UserController', function UserController($scope, $http) {


    $scope.username = null;
    $scope.password = null;
    $scope.email = null;
    $scope.postuser = function(username, password, email){
        var data = {

            username: username,
            password: password,
            email: email
        };


        $http.post("http://localhost:8081/auth/users", JSON.stringify(data)).then (function (response){
            if (response.data)
                $scope.msg = "Post Data Submitted Successfully!";

        }, function (response) {
            $scope.msg = JSON.stringify(data)
            $scope.statusval = response.status;
            $scope.statustext = response.statusText;
            $scope.headers = response.xhrStatus;


        })
    };

})

I have been trying to modify the http security expressions in the original code我一直在尝试修改原始代码中的 http 安全表达式

 @Override
    protected void configure(HttpSecurity http) throws Exception
    {
       //http.authorizeRequests().antMatchers("/h2-console/**").permitAll();
       http.requestMatchers().antMatchers("/login", "/oauth/authorize").and().authorizeRequests().anyRequest().authenticated().and().formLogin().permitAll();

       // http.requestMatchers().antMatchers("/login", "/oauth/authorize").and().authorizeRequests().antMatchers("/login").authenticated().and().formLogin().permitAll().and().authorizeRequests().antMatchers("/h2-console/**").anonymous();
        //http.authorizeRequests().antMatchers("/h2-console/**").anonymous();

       // http.requestMatchers().antMatchers("/login", "/oauth/authorize").and().authorizeRequests().anyRequest().
       // http.requestMatchers().antMatchers("/login", "/oauth/authorize");
        //http.authorizeRequests().anyRequest().authenticated().and().formLogin().permitAll();
        //http.antMatcher("/**").requestMatchers("/h2-console/**")

      // http.requestMatchers().antMatchers("/login", "/oauth/authorize");

     // http.authorizeRequests().antMatchers("/h2-console/**").permitAll();
            //  .requestMatchers().antMatchers("/login", "/oauth/authorize");

       // http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/h2-console/**").permitAll();
        //to run h2 might use profiles later
        http.csrf().disable();
        http.headers().frameOptions().disable();

    }

The things that are commented out are things that I have tried注释掉的都是我试过的

I have a controller in the Auth server that accepts POST requests.我在接受 POST 请求的 Auth 服务器中有一个 controller。 When I comment out the normal httpSecurity expressions and add code to disable csrf protection and disable headers, I can create accounts.当我注释掉正常的 httpSecurity 表达式并添加代码以禁用 csrf 保护和禁用标头时,我可以创建帐户。 (obviously this isn't a good solution) (显然这不是一个好的解决方案)

At this point I'm kinda stuck, I also suspect that this isn't at all the correct way of sending data to a secure server.在这一点上我有点卡住了,我还怀疑这根本不是将数据发送到安全服务器的正确方法。 But, I haven't been able to find any guides online但是,我一直无法在网上找到任何指南

So, can anybody help or point me in the right direction?那么,任何人都可以帮助或指出我正确的方向吗?

I came up with this line of code to get everything working我想出了这行代码来让一切正常

http
    .csrf().disable()
    .headers().frameOptions().disable()
        .and()
            .requestMatchers()
                .antMatchers("/login")
        .and()
            .authorizeRequests()
                .antMatchers("/login").authenticated()
        .and().formLogin().permitAll()
        .and()
            .requestMatchers()
                .antMatchers("/oauth/authorize")
        .and()
            .authorizeRequests()
                .antMatchers("/oauth/authorize").authenticated()
        .and().formLogin().permitAll()
        .and().requestMatchers()
            .antMatchers("/h2-console/**")
        .and().authorizeRequests()
            .antMatchers("/h2-console/**").permitAll()
        .and().requestMatchers()
            .antMatchers("/users")
        .and()
            .authorizeRequests().antMatchers("/users").permitAll()
        .and()
            .requestMatchers().antMatchers("/user/currentUser")
        .and()
            .authorizeRequests().antMatchers("/user/currentUser").permitAll();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM