0

I tried from the post PreAuthorize not working on Controller but its not working.

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

Then i got to know that without preauthorize code working fine if added preauthorize its showing error:org.springframework.security.access.AccessDeniedException in postman but in eclipse console no error.

Postman Request

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"
}

This my 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>
this is my config file.
@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");
  }
}
}
and user contoller

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**
}
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
ItsMj
  • 1
  • 1
  • Can you post the request? Go to postman --> Click Code(Right side below Save button). – Abdullah Khan Oct 26 '17 at 06:49
  • 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"} ------>this one right – ItsMj Oct 26 '17 at 07:07
  • after token generated ..im tryinng to acess the users in controller {"timestamp":1509002266027,"status":403,"error":"Forbidden","exception":"org.springframework.security.access.AccessDeniedException","message":"Access is denied","path":"/users"} – ItsMj Oct 26 '17 at 07:20
  • https://auth0.com/blog/securing-spring-boot-with-jwts/ from here i written the above code. – ItsMj Oct 26 '17 at 10:11

1 Answers1

0

If you want to have an authentication mechanism by JWT token, you have to add an AuthenticationProvider to your SecurityConfig and make the session stateless.

You can see this example: https://github.com/oharsta/spring-jwt

Nejib
  • 11
  • 1