小编Pat*_*mil的帖子

Spring Boot 安全性 - Postman 提供 401 Unauthorized

我正在 Spring Boot 中开发 rest API。我能够进行 CRUD 操作并且邮递员给出正确的响应,但是当我添加 Spring Security 用户名和密码时,邮递员给出 401 Unauthorized。

我提供了一个 spring boot 安全用户名和密码,如下所示。

application.proptries

spring.jpa.hibernate.ddl-auto=update
spring.datasource.platform=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/pal?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.security.user.name=root
spring.security.user.password=root
Run Code Online (Sandbox Code Playgroud)

我已经使用用户名作为 root 和密码作为 root 完成了基本身份验证。预览请求提供标题更新成功消息:

在此处输入图片说明

编辑 我已经删除了邮递员中的 cookie 但仍然面临同样的问题

SecurityConfing.java
My Security Configuration are as below. 
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.core.annotation.Order;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@Order(1000)
public class SecurityConfig extends WebSecurityConfigurerAdapter{


    public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception { …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-boot postman

11
推荐指数
1
解决办法
3万
查看次数

CORS 标头“Access-Control-Allow-Origin”缺少 REACT

我正在 Spring Boot 之上构建一个 React 应用程序。当我尝试向 localhost:8080 发出 put 请求时,我的浏览器出现了这些错误

跨域请求被阻止:同源策略不允许读取位于 http://localhost:8080/products 的远程资源。(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

跨域请求被阻止:同源策略不允许读取位于 http://localhost:8080/products 的远程资源。(原因:CORS请求没有成功)

我已经在我的服务器端为 localhost 3000 设置了@CrossOrigin。

通过添加标头、代理甚至在任何地方使用 firefox CORS 来解决这个问题已经有一段时间了。似乎没有任何工作。

请看下面我的前端代码

import React, { Component } from "react";
import { Card, Form, Button } from "react-bootstrap";
import axios from "axios";
import Toasting from "./Toasting";
export default class AddProducts extends Component {
  constructor(props) {
    super(props);
    this.state = this.startState;
    this.state.toast = false;
    this.productChange = this.productChange.bind(this);
    this.submitProduct = this.submitProduct.bind(this);
    var config = {
            headers: {'Access-Control-Allow-Origin': '*'}
        }; …
Run Code Online (Sandbox Code Playgroud)

spring cors reactjs spring-boot react-native

10
推荐指数
1
解决办法
1066
查看次数

javax.ws.rs.NotFoundException:无法找到完整路径的资源

windows 7(64);

jdk1.7.0_51(64);

RESTEasy3.0.7;

Apache的Tomcat的7.0.50;

项目名称:你好

RESTEasyHelloWorldService.java:

Windows 7(64)
jdk1.7.0_51(64)
RESTEasy3.0.7
apache-tomcat-7.0.50
Project Name: hello
Run Code Online (Sandbox Code Playgroud)

web.xml中:

package com.javacodegeeks.enterprise.rest.resteasy;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/RESTEasyHelloWorld")
public class RESTEasyHelloWorldService {

    @GET
    @Path("/{param}")
    @Produces(MediaType.TEXT_PLAIN)
    public String getMsg(@PathParam("param") String name) {
        String msg = "Rest say: good " + name;
        return msg;
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么我在调用http://localhost:8080/hello/rest/RESTEasyHelloWorld/a 返回时得到异常:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>hello</display-name>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <!-- Auto scan REST service -->
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param> …
Run Code Online (Sandbox Code Playgroud)

java resteasy

8
推荐指数
1
解决办法
3万
查看次数

Spring Boot 执行器 - MAX 属性

我正在使用 Spring Boot Actuator 依赖项来获取应用程序的见解。为此,我使用了 Spring Boot Admin。客户端-服务器的配置工作正常。我必须测量将要执行的端点的计数、总时间和最大值。

uri:/user/asset/getAllAssets
TOTAL_TIME: 831ms
MAX: 0ms 

uri:/user/getEmployee/{employeeId}
TOTAL_TIME: 98ms
MAX: 0ms
Run Code Online (Sandbox Code Playgroud)

为什么MAX(时间)是0而TOTAL_TIME:是Xms

Spring Boot 管理镜像

当我执行泛化形式时

localhost:8889/actuator/metrics/http.server.requests我得到的MAX 为 3.00..

我还看到了生产就绪功能,但找不到任何有关 MAX 是如何计算或它代表什么的描述

注:随着请求数量的增加,COUNT、TOTAL_TIME 也会增加,但 MAX 有时会减少(具体参见请求 1、请求 2)

请求1:http.server.requests

 {
        "name": "http.server.requests",
        "description": null,
        "baseUnit": "seconds",
        "measurements": [
            {
                "statistic": "COUNT",
                "value": 597
            },
            {
                "statistic": "TOTAL_TIME",
                "value": 144.9057076
            },
            {
                "statistic": "MAX",
                "value": 3.0002913
            }
        ],
        "availableTags": [
            {
                "tag": "exception",
                "values": [
                    "None"
                ]
            },
            {
                "tag": "method",
                "values": …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-boot-actuator spring-boot-admin

8
推荐指数
2
解决办法
6486
查看次数

RESTEASY003210:找不到完整路径的资源:Tomcat

我收到以下错误:

这是堆栈跟踪:

javax.ws.rs.NotFoundException: RESTEASY003210: Could not find resource for full path: http://localhost:9050/scenarioplanner/api/models/
    at org.jboss.resteasy.core.registry.ClassNode.match(ClassNode.java:75)
    at org.jboss.resteasy.core.registry.RootClassNode.match(RootClassNode.java:48)
    at org.jboss.resteasy.core.ResourceMethodRegistry.getResourceInvoker(ResourceMethodRegistry.java:445)
    at org.jboss.resteasy.core.SynchronousDispatcher.getInvoker(SynchronousDispatcher.java:257)
    at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:194)
    at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:221)
    at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
    at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Run Code Online (Sandbox Code Playgroud)

这是我的web.xml

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" …
Run Code Online (Sandbox Code Playgroud)

java tomcat resteasy maven servlet-3.0

7
推荐指数
1
解决办法
3万
查看次数

无法在h2内存数据库中插入数据

我正在内存数据库中插入数据,在插入数据时我遇到了问题,

使用 boot、JPA、H2db 在 inMemory 中插入数据的示例程序

  • 创建Pojo并使用JPA注释进行注释

  • 创建用于查询的 data.sql 文件。

  • 运行应用程序。请在屏幕截图中查找问题详细信息。

我尝试了多种方法,但仍然出现同样的异常

  • 在app.prop中配置:String url = jdbc:h2:~/test;DB_CLOSE_ON_EXIT=FALSE

  • 在 data.sql 文件中添加@Table给定表

  • 添加了@Columndata.sql 中提到的转换名称。

在哪里配置;DB_CLOSE_ON_EXIT=FALSE在 springboot 中?

波乔

@Entity
@Table(name = "exchange_value")
public class CurrencyExchange {
    @Id
    private Long id;
    @Column(name = "currency_from")
    private String from;
    @Column(name = "currency_to")
    private String to;
    @Column(name = "conversion_multiple")
    private BigDecimal conversion;
    private int port;
Run Code Online (Sandbox Code Playgroud)

控制器

@Autowired
    private Environment env;
    @GetMapping("/currency-exchange/from/{from}/to/{to}")
    public CurrencyExchange retriveCurrencyExchange(@PathVariable String from,@PathVariable String to)
    {
        CurrencyExchange …
Run Code Online (Sandbox Code Playgroud)

java database spring h2 spring-boot

7
推荐指数
2
解决办法
2万
查看次数

有没有办法以非交互模式运行 spring-shell 2.x

我们正在构建一个 spring-shell 应用程序。目前,在交互模式下,我必须像

java -jar sample.jar 
Run Code Online (Sandbox Code Playgroud)

shell:> mycommand arg1 agr2

有没有办法以交互方式运行这个修女,像这样

java -jar sample.jar mycommand arg1 agr2然后退出。

spring spring-shell

7
推荐指数
1
解决办法
1944
查看次数

Angular:当资产文件夹发生更改时防止自动重新编译

我正在尝试在 Angular 项目的资产中下载由 Spring Boot 生成的文件。当我从 Angular 服务调用 Spring API 时,Angular CLI 在 Assets Angular 文件夹中创建文件后重新编译项目,然后在从 Spring Boot API 获取响应之前重新加载页面。

我尝试通过多种方式从 Angular 调用 Spring Boot API:

  • 在我的组件的 ngOnInit() 中调用 api
  • 在我的组件的构造函数中调用 api
  • 在单独的函数中调用 api
  • 在下载功能中使用异步等待

我不知道如何继续

弹簧靴

 @GetMapping(path = "/downloads/{fileId}", produces = "application/json")
    @ResponseBody
    public ResponseEntity<String> download(@PathVariable String fileId){
        Gson gson = createGson();

        List<com.bioimis.blp.entity.File> fileById;

        try {
            fileById = fileRepository.findFileById(fileId);

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }

        if (fileById.isEmpty()) {
            logger.error(fileId + " not found");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        } …
Run Code Online (Sandbox Code Playgroud)

html livereload spring-boot angular

7
推荐指数
1
解决办法
3443
查看次数

Cookie CsrfTokenRepository.withHttpOnlyFalse() 做什么以及何时使用它?

我现在正在尝试学习 Spring Security,并且我已经看到许多使用它的不同示例。我知道 CSRF 是什么,并且 Spring Security 默认启用它。我很想知道的是这种定制。

  .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
  .and()
  .authorizeRequests(request -> {
                request
                    .antMatchers("/login").permitAll()
                    .anyRequest()
                    ....more code
Run Code Online (Sandbox Code Playgroud)

.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())条线做了什么样的定制,什么时候适合使用。如果有人能提供一个简单的解释,我将不胜感激。

java spring csrf spring-security spring-boot

7
推荐指数
1
解决办法
3820
查看次数

父级上没有外键的子级的级联插入

我在互联网上查了很多帖子,但都没有解决我的问题.如果有人能提供帮助,真的很感激!我有OneToMany父子关系.当其中一个子组合键是父组件(Level1)的外键时,Hibernate不会级联插入子级(Level2).我指定了cascade ="all",无论逆是true还是false,结果都是一样的.没有例外,它只是不插入.下面的打印显示Level1已成功插入,但Level2仅被选中,没有插入.

Hibernate:插入sst.level_1(STATUS,NAME)值(?,?)Hibernate:从sst.level_2 level2x_中选择level2x_.LEVEL_1_ID,level2x_.TIMESEGMENT,level2x_.CATEGORY为CATEGORY4_,其中level2x_.LEVEL_1_ID =?和level2x_.TIMESEGMENT =?

API是Hibernate 4.1.6/Spring 3.1.2.

这是mySQL的表定义:

Hibernate: insert into sst.level_1 (STATUS, NAME) values (?, ?)
Hibernate: select level2x_.LEVEL_1_ID, level2x_.TIMESEGMENT, level2x_.CATEGORY as CATEGORY4_ from sst.level_2 level2x_ where level2x_.LEVEL_1_ID=? and level2x_.TIMESEGMENT=?
Run Code Online (Sandbox Code Playgroud)

这是测试代码.

CREATE TABLE level_1
(
ID int NOT NULL PRIMARY KEY AUTO_INCREMENT,
STATUS int,
NAME varchar(255)
);

CREATE TABLE level_2
(
LEVEL_1_ID int,
TIMESEGMENT int,
CATEGORY varchar(2),
PRIMARY KEY (LEVEL_1_ID, TIMESEGMENT),
FOREIGN KEY (LEVEL_1_ID) REFERENCES level_1(ID) ON DELETE CASCADE
);
Run Code Online (Sandbox Code Playgroud)

Level1的映射:

public class Test {

   public static …
Run Code Online (Sandbox Code Playgroud)

hibernate cascade foreign-keys one-to-many

6
推荐指数
1
解决办法
9658
查看次数