spring - 找不到使用域类资源创建的Grails REST API返回

标签 spring rest grails groovy

我正在尝试为用户编辑创建REST api。
我决定使用文档中描述的方法:
https://docs.grails.org/3.3.11/guide/REST.html#domainResources(我使用的是较旧的grailsVersion = 3.3.11)
因此,我继续创建了这样的域类(域类是由grails s2-quickstart com.mastiko.auth用户角色创建的)

package com.mastiko.auth


import grails.rest.Resource

@Resource(uri = '/api/users', formats=['json'])
class User implements Serializable {

    private static final long serialVersionUID = 1

    String username
    String password
    String mems****ApiUser
    String mems****ApiPassword
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    Set<Role> getAuthorities() {
        (UserRole.findAllByUser(this) as List<UserRole>)*.role as Set<Role>
    }

    static constraints = {
        password nullable: false, blank: false, password: true
        username nullable: false, blank: false, unique: true
    }

    static mapping = {
        password column: '`password`'
    }
}
我的application.groovy看起来像这样:


// Added by the Spring Security Core plugin:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.mastiko.auth.User'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.mastiko.auth.UserRole'
grails.plugin.springsecurity.authority.className = 'com.mastiko.auth.Role'
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
    [pattern: '/',               access: ['permitAll']],
    [pattern: '/dbconsole/**',   access: ['permitAll']],
    [pattern: '/error',          access: ['permitAll']],
    [pattern: '/index',          access: ['permitAll']],
    [pattern: '/index.gsp',      access: ['permitAll']],
    [pattern: '/shutdown',       access: ['permitAll']],
    [pattern: '/assets/**',      access: ['permitAll']],
    [pattern: '/**/js/**',       access: ['permitAll']],
    [pattern: '/**/css/**',      access: ['permitAll']],
    [pattern: '/**/images/**',   access: ['permitAll']],
    [pattern: '/**/favicon.ico', access: ['permitAll']]
]

grails.plugin.springsecurity.filterChain.chainMap = [
    [pattern: '/assets/**',      filters: 'none'],
    [pattern: '/**/js/**',       filters: 'none'],
    [pattern: '/**/css/**',      filters: 'none'],
    [pattern: '/**/images/**',   filters: 'none'],
    [pattern: '/**/favicon.ico', filters: 'none'],
    [pattern: '/**',             filters: 'JOINED_FILTERS']
]
另外,我将此配置添加到application.yml中,因为没有它我就无法使spring security rest api插件正常工作
plugin:
  springsecurity:
    controllerAnnotations:
      chainMap:
        '/api/**': 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter'
        '/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter'
我的UrlMappings.groovy:
package mems****eprojects (censored)

class UrlMappings {

    static mappings = {
        delete "/$controller/$id(.$format)?"(action:"delete")
        get "/$controller(.$format)?"(action:"index")
        get "/$controller/$id(.$format)?"(action:"show")
        post "/$controller(.$format)?"(action:"save")
        put "/$controller/$id(.$format)?"(action:"update")
        patch "/$controller/$id(.$format)?"(action:"patch")

        "/"(controller: 'application', action:'index')
    }
}
现在,当我尝试使用对http:// localhost:8080 / api / users的POST请求访问我的api时,总是得到404 not found响应:
{
    "timestamp": 1598893213831,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/api/users"
}
我尝试了一个命令grails url-mappings-report,并且得到了肯定的结果:
Dynamic Mappings
 |   GET    | /${controller}(.${format)?            | Action: index                 |
 |   POST   | /${controller}(.${format)?            | Action: save                  |
 |  DELETE  | /${controller}/${id}(.${format)?      | Action: delete                |
 |   GET    | /${controller}/${id}(.${format)?      | Action: show                  |
 |   PUT    | /${controller}/${id}(.${format)?      | Action: update                |
 |  PATCH   | /${controller}/${id}(.${format)?      | Action: patch                 |

Controller: application
 |    *     | /                                     | Action: index                 |

Controller: restOauth
 |    *     | /oauth/access_token                   | Action: accessToken           |
 |    *     | /oauth/${action}/${provider}          | Action: (default action)      |

Controller: user
 |   GET    | /api/users/create                     | Action: create                |
 |   GET    | /api/users/${id}/edit                 | Action: edit                  |
 |   POST   | /api/users                            | Action: save                  |
 |   GET    | /api/users                            | Action: index                 |
 |  DELETE  | /api/users/${id}                      | Action: delete                |
 |  PATCH   | /api/users/${id}                      | Action: patch                 |
 |   PUT    | /api/users/${id}                      | Action: update                |
 |   GET    | /api/users/${id}                      | Action: show                  |

我是新手,这是我的第一个应用程序。
很抱歉,如果缺少一些重要的代码,我将在需要时将其发布。你能帮我么?我已经尝试了好几个小时了。
//编辑1
我忘记添加我的build.gradle
buildscript {
    repositories {
        mavenLocal()
        maven { url "https://repo.grails.org/grails/core" }
        maven { url "https://plugins.gradle.org/m2/" }
    }
    dependencies {
        classpath "org.grails:grails-gradle-plugin:$grailsVersion"
        classpath "com.moowork.gradle:gradle-node-plugin:1.2.0"
        classpath "org.grails.plugins:hibernate5:${gormVersion-".RELEASE"}"
        classpath "org.grails.plugins:views-gradle:1.2.9"
    }
}

version "0.1"
group "mem****eprojects"

apply plugin:"eclipse"
apply plugin:"idea"
apply plugin:"war"
apply plugin:"org.grails.grails-web"
apply plugin:"com.moowork.node"
apply plugin:"org.grails.plugins.views-json"

repositories {
    mavenLocal()
    maven { url "https://repo.grails.org/grails/core" }
}

dependencies {
    compile "org.springframework.boot:spring-boot-starter-logging"
    compile "org.springframework.boot:spring-boot-autoconfigure"
    compile "org.grails:grails-core"
    compile "org.springframework.boot:spring-boot-starter-actuator"
    compile "org.springframework.boot:spring-boot-starter-tomcat"
    compile "org.grails:grails-plugin-url-mappings"
    compile "org.grails:grails-plugin-rest"
    compile "org.grails:grails-plugin-codecs"
    compile "org.grails:grails-plugin-interceptors"
    compile "org.grails:grails-plugin-services"
    compile "org.grails:grails-plugin-datasource"
    compile "org.grails:grails-plugin-databinding"
    compile "org.grails:grails-web-boot"
    compile "org.grails:grails-logging"
    compile "org.grails.plugins:cache"
    compile "org.grails.plugins:async"
    compile "org.grails.plugins:hibernate5"
    compile "org.hibernate:hibernate-core:5.1.16.Final"
    compile "org.grails.plugins:views-json"
    compile "org.grails.plugins:views-json-templates"
    compile "org.grails.plugins:spring-security-core:3.2.0"
    compile "org.grails.plugins:spring-security-rest:2.0.0.M2"
    console "org.grails:grails-console"
    profile "org.grails.profiles:vue"
    runtime "org.glassfish.web:el-impl:2.1.2-b03"
    runtime "com.h2database:h2"
    runtime "org.apache.tomcat:tomcat-jdbc"
    testCompile "org.grails:grails-gorm-testing-support"
    testCompile "org.grails:grails-datastore-rest-client"
    testCompile "org.grails:grails-web-testing-support"
}

bootRun {
    jvmArgs('-Dspring.output.ansi.enabled=always')
    addResources = true
    String springProfilesActive = 'spring.profiles.active'
    systemProperty springProfilesActive, System.getProperty(springProfilesActive)
}

我添加了spring-security-rest插件,以便能够使用/ api / login端点从vuejs前端进行身份验证。我检索了 token ,然后尝试使用 header 中的 token 向/ api / users端点发出请求。所以问题可能出在这个插件上

最佳答案

所以我能够解决这个问题,从application.yml中删除下面的代码

plugin:
  springsecurity:
    controllerAnnotations:
      chainMap:
        '/api/**': 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter'
        '/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter'
并将代码添加到application.groovy
grails.plugin.springsecurity.filterChain.chainMap = [
        //Stateless chain
        [ pattern: '/api/**', filters: 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter'],

        //Traditional chain
        //[ pattern: '/**', filters: 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter']
]
我不确定我为什么首先将chainMap放在application.yml中。
感谢您阅读本文并尽力帮助我

关于spring - 找不到使用域类资源创建的Grails REST API返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63675335/

相关文章:

java - 我应该在生产中使用什么 tomcat native 库?

java - Spring security - authorizerequest()、anyRequest() 和authenticated() 有什么作用?

spring - ContextRefreshedEvent、ContextStartedEvent、ContextStoppedEvent 和 ContextClosedEvent 有什么区别

java - 为什么类路径默认为 WEB-INF/classes/而不是 JBoss 5.1 中的 WEB-INF/?

java - Spring 启动 |多个调度程序 Servlet

spring-boot - Spring boot更新数据库记录时出现 "Operation is not supported for read-only collection"

WCF Restful 帖子

Grails、Vaadin 7 和 SpringSecurity : authorization not working

grails - 无法测试在 LAN 内具有 oauth autontication 的 Grails 应用程序

javascript - 如何将值直接从 Controller 传递到 Grails 中的 javascript 文件