【问题标题】:@PreAuthorize not working on controller help me out@PreAuthorize 不在控制器上工作帮助我
【发布时间】:2018-04-07 10:07:33
【问题描述】:

我从PreAuthorize not working on Controller 的帖子中尝试过,但它不起作用。

{ 
    "timestamp": 1509002266027, 
    "status": 403, 
    "error": "Forbidden", 
    "exception": "org.springframework.security.access.AccessDeniedException", 
    "message": "Access is denied", 
    "path": "/users" 
}

然后我知道,如果添加预授权显示错误:org.springframework.security.access.AccessDeniedException 在邮递员中但在 Eclipse 控制台中没有错误,则没有预授权代码可以正常工作。

邮递员请求

POST /login HTTP/1.1 
Host: localhost:8080 
Content-Type: application/json 
Cache-Control: no-cache 
Postman-Token: 8b702acb-a5c6-618f-b32a-4c168139ac13 

{
    "username":"admin",
    "password":"password"
}

这是我的 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.7.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
	<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.7.0</version>
</dependency>
	
	
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>
这是我的配置文件。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends GlobalMethodSecurityConfiguration {
	
	@Configuration
    public static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
  protected void configure(HttpSecurity http) throws Exception {
		
    http.csrf().disable().authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers(HttpMethod.POST, "/login").permitAll()
        .antMatchers(HttpMethod.POST, "/signin").hasRole("USER")
        .anyRequest().authenticated()
        .and()
        // We filter the api/login requests
        .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
                UsernamePasswordAuthenticationFilter.class)
        // And filter other requests to check the presence of JWT in header
        .addFilterBefore(new JWTAuthenticationFilter(),
                UsernamePasswordAuthenticationFilter.class)
    .addFilterBefore(new JWTLoginFilter("/signin", authenticationManager()),
            UsernamePasswordAuthenticationFilter.class)
    // And filter other requests to check the presence of JWT in header
    .addFilterBefore(new JWTAuthenticationFilter(),
            UsernamePasswordAuthenticationFilter.class);
  }
	
	 
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // Create a default account
    auth.inMemoryAuthentication()
        .withUser("admin")
        .password("password")
        .roles("ADMIN").and(). 
        withUser("manoj")
        .password("manoj")
        .roles("USER");
  }
}
}
和用户控制器

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class UserController {

  /* Maps to all HTTP actions by default (GET,POST,..)*/
	@PreAuthorize("hasRole('ADMIN')")
  @RequestMapping("/users")
  public @ResponseBody String getUsers() {
    return "{\"users\":[{\"firstname\":\"Manoj\", \"lastname\":\"velaga\"}," +
           "{\"firstname\":\"Abhishek\",\"lastname\":\"Muthyam\"}]}";
  }
  
  
  
  @RequestMapping("/myusers")
  public @ResponseBody String getUsers1() {
    return "{\"users\":[{\"firstname\":\"Manoj\", \"lastname\":\"xxx\"}," +
           "{\"firstname\":\"Abhishek\",\"lastname\":\"yyyy\"}]}";
  }
  **strong text**
}

【问题讨论】:

  • 您可以发布请求吗?转到邮递员->单击代码(保存按钮下方的右侧)。
  • POST /login HTTP/1.1 主机:localhost:8080 内容类型:application/json 缓存控制:无缓存 Postman-Token:8b702acb-a5c6-618f-b32a-4c168139ac13 {"username" :"admin","password":"password"} ------>这一项对
  • 生成令牌后..我试图访问控制器中的用户 {"timestamp":1509002266027,"status":403,"error":"Forbidden","exception":"org.springframework .security.access.AccessDeniedException","message":"访问被拒绝","path":"/users"}
  • auth0.com/blog/securing-spring-boot-with-jwts 从这里我写了上面的代码。

标签: javascript java spring maven


【解决方案1】:

如果您想通过 JWT 令牌获得身份验证机制,则必须将 AuthenticationProvider 添加到您的 SecurityConfig 并使会话无状态。

你可以看这个例子:https://github.com/oharsta/spring-jwt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2015-08-12
    • 2012-08-11
    • 2010-11-08
    • 2015-10-12
    • 2015-10-12
    相关资源
    最近更新 更多