我正在尝试使用 Spring 安全性来制作 REST API 的基本示例。我正在使用 Grails 插件 spring-security-rest:2.0.0.M2
我尝试遵循这个优秀的教程,但遇到了范围不足的错误。
我正在定义一个角色 ADMIN_ROLE。成功登录后,我得到一个access_token
我已@Secured(['ROLE_ADMIN'])在 ProjectController 类中添加了标签:
@Secured(['ROLE_ADMIN'])
class ProjectController extends RestfulController {
static responseFormats = ['json', 'xml']
ProjectController() {
super(Project)
}
def active() {
respond Project.findAllByActive(true), view: 'index'
}
}
Run Code Online (Sandbox Code Playgroud)
我的 UrlMappings 指向 ProjectController:包 dk.mathmagicians.demo
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
"/projects"(resources:"project")
"/active"(controller: 'project', action: 'active')
"/"(view: '/index')
"500"(view: '/error')
"404"(view: '/notFound')
}
}
Run Code Online (Sandbox Code Playgroud)
我已经使用过滤器配置了 application.groovy 文件,如下所示 …
我正在使用Grails Rest应用。我正在使用的grails版本是3.3.1。我正在使用spring-security-rest进行授权。我已经使用s2-quickstart命令创建了以下类。
该应用程序运行良好,但User类的单元测试失败,控制台中出现以下错误。
java.lang.IllegalStateException: Either class [hungr.Authority] is not a domain class or GORM has not been initialized correctly or has already been shutdown. Ensure GORM is loaded and configured correctly before calling any methods on a GORM entity.
at org.grails.datastore.gorm.GormEnhancer.stateException(GormEnhancer.groovy:469)
at org.grails.datastore.gorm.GormEnhancer.findStaticApi(GormEnhancer.groovy:300)
at org.grails.datastore.gorm.GormEnhancer.findStaticApi(GormEnhancer.groovy:296)
at org.grails.datastore.gorm.GormEntity$Trait$Helper.currentGormStaticApi(GormEntity.groovy:1349)
at org.grails.datastore.gorm.GormEntity$Trait$Helper.staticMethodMissing(GormEntity.groovy:756)
at hungr.UserController.$tt__save(UserController.groovy:39)
at hungr.UserController.save_closure1(UserController.groovy)
at groovy.lang.Closure.call(Closure.java:414)
at groovy.lang.Closure.call(Closure.java:430)
at grails.gorm.transactions.GrailsTransactionTemplate$2.doInTransaction(GrailsTransactionTemplate.groovy:94)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at grails.gorm.transactions.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:91)
at org.grails.testing.runtime.support.ActionSettingMethodHandler.invoke(ActionSettingMethodHandler.groovy:28)
at hungr.UserControllerSpec.Test the save action correctly persists(UserControllerSpec.groovy:90)
Run Code Online (Sandbox Code Playgroud)
我尝试在GORM上参考答案,但未能意识到插件中的Domain类是GORM类, 但没有任何效果。我是新来的grails,因此我不知道可能出什么问题了。我正在使用的类是: …
我正在开发一个应用程序,其前端是使用React.js编写的,后端REST API是使用Spring框架编写的。我想将社交登录信息添加到我的网站,因此经过数天的搜索和研究,我了解到OAuth2是解决方案。我知道前端应处理从资源服务器(此处为Facebook)获取授权令牌的过程,而后端(java)应验证该令牌并与Facebook连接以获取访问令牌。然后,该访问令牌应与用户详细信息(例如电子邮件)一起存储在我的数据库中。
这是我的要求,一旦用户单击“通过Facebook继续”按钮,我的应用程序应使用详细信息-电子邮件和姓名(注册功能)在我自己的数据库中创建该帐户。之后,每当他们再次单击该按钮时,他们将登录并没有注册。其他网站处理它的方式。
到目前为止,我的应用程序中已有该按钮,这使我从Facebook获得了授权令牌。
有人可以指导我在这里走的路吗?
另外,对于某些错误处理,我应该特别注意。
spring-boot spring-security-oauth2 spring-security-rest spring-oauth2
我正在编写一个过滤器,该过滤器将拦截Restful API调用,提取Bearer令牌并调用Authorization Server进行验证。
我在Spring Boot中找不到一个可以直接使用的工具,但是我敢肯定有一种更干净的方法可以做到这一点。这是我所拥有的(伪代码):
public class SOOTokenValidationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String xAuth = request.getHeader("Authorization");
// validate the value in xAuth
if(isValid(xAuth) == false){
throw new SecurityException();
}
// Create our Authentication and set it in Spring
Authentication auth = new Authentication ();
SecurityContextHolder.getContext().setAuthentication(auth);
filterChain.doFilter(request, response);
}
private boolean isValid (String token){
// make a call to SSO passing the access token and
// return true if …Run Code Online (Sandbox Code Playgroud) 我有一个自定义 Spring Security 过滤器,它被多次调用,但我不明白为什么。我搜索了它并尝试FilterRegistrationBean按照一些帖子的建议添加,但我的安全过滤器仍然被多次调用并抛出以下错误 -
20:57:49.975 [http-nio-8888-exec-2] DEBUG c.s.m.security.RESTSecurityFilter - Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fb70fff6: Principal: srib; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@43458: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: BC1D5AB21EE4586F2A76C7901F1F953F; Granted Authorities: ROLE_USER, ROLE_ADMIN
20:57:50.220 [http-nio-8888-exec-2] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendError() after the response has been committed] with root cause
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed …Run Code Online (Sandbox Code Playgroud) 我想将用户ID字段添加到从/ api/login返回的令牌
目前它是:
{
"username": "user",
"roles": [
"ROLE_USER"
],
"token_type": "Bearer",
"access_token": "eyJhbGciOiJIUzI1NiJ9.2uk2YoHsyd7bqUdtUYN19ef..",
"expires_in": 3600,
"refresh_token": "eyJhbGciOiJIUzI1NiJ9.eyJwcmluY2lwYWwiOiJINH.."
}
Run Code Online (Sandbox Code Playgroud)
我需要:
{
"id": "1",
"username": "user",
"roles": [
"ROLE_USER"
],
"token_type": "Bearer",
"access_token": "eyJhbGciOiJIUzI1NiJ9.2uk2YoHsyd7bqUdtUYN19ef..",
"expires_in": 3600,
"refresh_token": "eyJhbGciOiJIUzI1NiJ9.eyJwcmluY2lwYWwiOiJINH.."
}
Run Code Online (Sandbox Code Playgroud)
目标 - 具有用户ID的查询,如POST/api/something有没有其他方法?提前致谢
我有一个安全的 Spring Boot 应用程序。我已经删除了这个“/login”网址的身份验证。
我的安全配置
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final JwtFilter jwtFilter;
@Autowired
public SecurityConfiguration(JwtFilter jwtFilter) {
this.jwtFilter = jwtFilter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.anonymous().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.apply(new JwtConfigurerAdapter(jwtFilter)).and()
.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs");
web.ignoring().antMatchers("/login");
}
}
Run Code Online (Sandbox Code Playgroud)
我的 NotFound 异常
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFound extends RuntimeException {
public NotFound(String message) {
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
我的带有登录 url 和异常返回值的休息控制器
@RestController
public class …Run Code Online (Sandbox Code Playgroud) java exception-handling spring-security spring-boot spring-security-rest
我想通过创建一个简单的登录屏幕在我的项目中使用 Spring Boot Security,但在运行应用程序时出现这些错误
描述:com.panchmeru_studio.controller.UserController 中构造函数的参数 1 需要类型为“org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder”的 bean,但无法找到。
操作:考虑在配置中定义 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' 类型的 bean。 这是我的代码。
用户控制器
package com.panchmeru_studio.controller;
import com.panchmeru_studio.entities.ApplicationUser;
import com.panchmeru_studio.repository.ApplicationUserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
private ApplicationUserRepository applicationUserRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;
public UserController(ApplicationUserRepository applicationUserRepository,
BCryptPasswordEncoder bCryptPasswordEncoder) {
this.applicationUserRepository = applicationUserRepository;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@PostMapping("/record")
public void signUp(@RequestBody ApplicationUser applicationUser) {
applicationUser.setPassword(bCryptPasswordEncoder.encode(applicationUser.getPassword()));
applicationUserRepository.save(applicationUser);
}
}
Run Code Online (Sandbox Code Playgroud)
安全配置.java
package com.panchmeru_studio.security;
import com.panchmeru_studio.filter.AuthenticationFilter;
import com.panchmeru_studio.filter.AuthorizationFilter;
import com.panchmeru_studio.service.ApplicationUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; …Run Code Online (Sandbox Code Playgroud) java spring spring-security spring-boot spring-security-rest