简体   繁体   English

Grails REST API 使用域创建 class 未找到资源返回

[英]Grails REST API created using domain class resource returns not found

I am trying to create a REST api for user editing.我正在尝试创建一个 REST api 供用户编辑。

I decided to use approach described in documentation:我决定使用文档中描述的方法:

https://docs.grails.org/3.3.11/guide/REST.html#domainResources (I am using older grailsVersion=3.3.11) https://docs.grails.org/3.3.11/guide/REST.html#domainResources (我使用的是旧版 grailsVersion=3.3.11)

So I went ahead and I created the domain class like this (domain class was created by command grails s2-quickstart com.mastiko.auth User Role)所以我继续,我像这样创建了域 class(域 class 是由命令 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`'
    }
}

My application.groovy looks like this:我的 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']
]

Also, I added this configuration into application.yml, as I wasnt able to make the spring security rest api plugin work without it此外,我将此配置添加到 application.yml 中,因为没有它我无法使 spring security rest api 插件工作

plugin:
  springsecurity:
    controllerAnnotations:
      chainMap:
        '/api/**': 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter'
        '/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter'

My UrlMappings.groovy:我的 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')
    }
}

Now, when I try to access my api using POST request to http://localhost:8080/api/users, I always get 404 not found response:现在,当我尝试使用对 http://localhost:8080/api/users 的 POST 请求访问我的 api 时,我总是得到 404 not found 响应:

{
    "timestamp": 1598893213831,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/api/users"
}

I tried a command grails url-mappings-report, and I get a positive result:我尝试了命令 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                  |

I am pretty new into grails and this is my very first application.我是 grails 的新手,这是我的第一个应用程序。

I am sorry if some important part of code is missing, I will post it if needed.如果缺少某些重要的代码部分,我很抱歉,如果需要,我会发布。 Can you please help me?你能帮我么? I was trying to figure this out for hours now..几个小时以来,我一直在努力解决这个问题。

//edit 1 I forgot to add my build.gradle //编辑 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)
}

I added spring-security-rest plugin to be able to authenticate myself from my vuejs frontend using /api/login endpoint.我添加了 spring-security-rest 插件,以便能够使用 /api/login 端点从我的 vuejs 前端对自己进行身份验证。 I retrieve the token, and then I am trying to make request to /api/users endpoint with the token in header. So maybe the issue is maybe caused by this plugin我检索了令牌,然后我尝试使用 header 中的令牌向 /api/users 端点发出请求。所以问题可能是由这个插件引起的

So I was able to fix this removing code bellow from application.yml所以我能够修复这个从 application.yml 中删除的代码

plugin:
  springsecurity:
    controllerAnnotations:
      chainMap:
        '/api/**': 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter'
        '/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter'

and adding code bellow to application.groovy并将下面的代码添加到 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']
]

I am not really sure why I put chainMap in application.yml in the first place.我不太确定为什么我首先将 chainMap 放在 application.yml 中。

Thank you for reading this and tryhing to help me感谢您阅读本文并尝试帮助我

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

相关问题 GET a sub resource of a Spring Data REST API 返回404 Not Found - GET a sub resource of a Spring Data REST API returns 404 Not Found Grails 2.4.5:你如何创建一个 Grails REST controller 没有链接到任何域和一个返回 object 不是域 class 的操作? - Grails 2.4.5: How do you create a Grails REST controller not linked to any domain and an action that returns an object that is not a domain class? 具有多个资源类的Spring / Jersey Rest API返回404 - Spring/Jersey Rest API with multiple resource class returns 404 在 Rest API 中找不到处理资源 - Handle Resource not found in Rest API Grails 3.x:重用JPA / Hibernate Domain类:找不到域类 - Grails 3.x: Re-using JPA/Hibernate Domain classes: Domain class not found 带有 MultipartFormDataInput 的 REST API 返回 404 - 未找到 - REST API with MultipartFormDataInput returns 404 - Not Found 使用REST根资源类作为接口,获取“无操作匹配请求” - Using REST root resource class as interface, getting “no operation matching request” 使用Activiti REST API部署动态创建的BPMN模型 - Deploying dynamically created BPMN model using Activiti REST API 尝试从Shell使用Grails域类 - Trying to use a grails domain class from the shell 服务没有注入Grails域类,Grails 2.0.0和2.0.3 - Service is not getting injected into Grails domain class , Grails 2.0.0 and 2.0.3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM