Grails, Spring Security - импорт контроллера входа не работает
Я начал новый проект Grails (2.4.4) в intellij и добавил compile ":spring-security-core:2.0.0"
установить пружину безопасности - это работало нормально. Я тогда побежал s2-quickstart io.mylife.feedmyface User Role
для генерации доменных классов User, Role и UserRole - это тоже отлично работало, я даже успешно загрузил пару ролей и пользователей. Затем я скопировал контроллеры входа и выхода, а также представления входа из target/work/plugins/spring-security-core-2.0.0/grails-app/controllers/grails/plugin/springsecurity
а также target/work/plugins/spring-security-core-2.0.0/grails-app/views/login
соответственно. Вот где возникает проблема. Многие из импорта, а также другие ключевые слова помечены красным как intellij, давая всплывающее окно cannot resolve symbol 'Secured'
, например. Во взглядах я получаю пару похожих ошибок, например <div class='errors'><g:message code="springSecurity.denied.message" /></div>
, springSecurity.denied.message
будет отмечен красным с помощью всплывающего окна cannot resolve property key
, Я меньше беспокоюсь о взглядах, хотя в прошлом я заметил, что сгенерированный код делает это иногда без особых проблем. Я просто хотел бы узнать, как починить контроллеры. Просто чтобы покрыть мои базы, я упомяну, что я использую Postgresql db, но я сомневаюсь, что это меняет дело? Пожалуйста, дайте мне знать, если мне нужно предоставить больше информации. Вот код контроллера:
LoginController:
/* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mylife.feedmyface
import grails.converters.JSON
import javax.servlet.http.HttpServletResponse
/* 'security is red on all of the below imports'*/
import org.springframework.security.access.annotation.Secured
import org.springframework.security.authentication.AccountExpiredException
import org.springframework.security.authentication.CredentialsExpiredException
import org.springframework.security.authentication.DisabledException
import org.springframework.security.authentication.LockedException
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.web.WebAttributes
@Secured('permitAll') // 'Secured' is red
class LoginController {
/**
* Dependency injection for the authenticationTrustResolver.
*/
def authenticationTrustResolver
/**
* Dependency injection for the springSecurityService.
*/
def springSecurityService
/**
* Default action; redirects to 'defaultTargetUrl' if logged in, /login/auth otherwise.
*/
def index() {
if (springSecurityService.isLoggedIn()) {
redirect uri: SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl
}
else {
redirect action: 'auth', params: params
}
}
/**
* Show the login page.
*/
def auth() {
def config = SpringSecurityUtils.securityConfig
if (springSecurityService.isLoggedIn()) {
redirect uri: config.successHandler.defaultTargetUrl
return
}
String view = 'auth'
String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
render view: view, model: [postUrl: postUrl,
rememberMeParameter: config.rememberMe.parameter]
}
/**
* The redirect action for Ajax requests.
*/
def authAjax() {
response.setHeader 'Location', SpringSecurityUtils.securityConfig.auth.ajaxLoginFormUrl
response.sendError HttpServletResponse.SC_UNAUTHORIZED
}
/**
* Show denied page.
*/
def denied() {
if (springSecurityService.isLoggedIn() &&
authenticationTrustResolver.isRememberMe(SCH.context?.authentication)) {
// have cookie but the page is guarded with IS_AUTHENTICATED_FULLY
redirect action: 'full', params: params
}
}
/**
* Login page for users with a remember-me cookie but accessing a IS_AUTHENTICATED_FULLY page.
*/
def full() {
def config = SpringSecurityUtils.securityConfig
render view: 'auth', params: params,
model: [hasCookie: authenticationTrustResolver.isRememberMe(SCH.context?.authentication),
postUrl: "${request.contextPath}${config.apf.filterProcessesUrl}"]
}
/**
* Callback after a failed login. Redirects to the auth page with a warning message.
*/
def authfail() {
String msg = ''
def exception = session[WebAttributes.AUTHENTICATION_EXCEPTION]
if (exception) {
if (exception instanceof AccountExpiredException) { // 'AccountExpiredException' is red
msg = g.message(code: "springSecurity.errors.login.expired")
}
else if (exception instanceof CredentialsExpiredException) { // 'CredentialsExpiredException' is red
msg = g.message(code: "springSecurity.errors.login.passwordExpired")
}
else if (exception instanceof DisabledException) { // 'DisabledException' is red
msg = g.message(code: "springSecurity.errors.login.disabled")
}
else if (exception instanceof LockedException) { // 'LockedException' is red
msg = g.message(code: "springSecurity.errors.login.locked")
}
else {
msg = g.message(code: "springSecurity.errors.login.fail")
}
}
if (springSecurityService.isAjax(request)) {
render([error: msg] as JSON)
}
else {
flash.message = msg
redirect action: 'auth', params: params
}
}
/**
* The Ajax success redirect url.
*/
def ajaxSuccess() {
render([success: true, username: springSecurityService.authentication.name] as JSON)
}
/**
* The Ajax denied redirect url.
*/
def ajaxDenied() {
render([error: 'access denied'] as JSON)
}
}
LogoutController:
/* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mylife.feedmyface
import javax.servlet.http.HttpServletResponse
/* Again, 'security' is red */
import org.springframework.security.access.annotation.Secured
import org.springframework.security.web.RedirectStrategy
@Secured('permitAll') // 'Secured' is red
class LogoutController {
/** Dependency injection for RedirectStrategy. */
RedirectStrategy redirectStrategy // 'RedirectStrategy' is red
/**
* Index action. Redirects to the Spring security logout uri.
*/
def index() {
if (!request.post && SpringSecurityUtils.getSecurityConfig().logout.postOnly) {
response.sendError HttpServletResponse.SC_METHOD_NOT_ALLOWED // 405
return
}
// TODO put any pre-logout code here
redirectStrategy.sendRedirect request, response, SpringSecurityUtils.securityConfig.logout.filterProcessesUrl // '/j_spring_security_logout'
response.flushBuffer()
}
}
1 ответ
Нет необходимости копировать контроллеры входа и выхода. После создания примера пользователей и ролей в bootstrap.groovy вам просто нужно настроить разрешения для ваших пользовательских контроллеров, используя аннотацию @secure или отображение запросов в config.groovy. Для получения дополнительной информации вы можете следовать этому руководству в документации плагинов.