弹簧安全弹簧安全休息api

时间:2017-02-17 13:21:51

标签: java spring spring-boot spring-security

我有网络应用程序,我想保护我的其余API我遵循一些教程,我成功实现其余的API是安全的。 但当我第一次调用这些页面时,我在我的网络应用程序中添加了html文件,它向我显示了要输入的登录区域。 我只想保证其余的API不是所有的网络应用程序 在我的情况下,这是我的application.properties

spring.datasource.url=jdbc:mysql://localhost/geekycoders_myteam
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
logging.level.org.springframework.boot.autoconfigure.security=INFO
security.user.name=admin
security.user.password=admin

这是我的SecurityConfig班级

public class SecurityConfig extends WebSecurityConfigurerAdapter {
      @Override
      protected void configure(HttpSecurity http) throws Exception {
        http
          .csrf().disable()
          .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/api/**").authenticated()
            .antMatchers(HttpMethod.PUT, "/api/**").authenticated()
            .antMatchers(HttpMethod.DELETE, "/api/**").authenticated()
            .antMatchers(HttpMethod.GET, "/api/**").authenticated()
            .anyRequest().permitAll()
            .and()
          .httpBasic().and()
          .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
      }
    }

这是一个样本控制器

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserRepository userRepository;

    @RequestMapping("/findall")
    @ResponseBody
    public List<User> findall(){
        return userRepository.findAll();

    }
    @RequestMapping("/find")
    @ResponseBody
    public User getUser(@PathParam("id") int id){
        return userRepository.findOne(id);
    }

}

我将index.html放到目录webapp中一些帮助

3 个答案:

答案 0 :(得分:0)

如果有人现在正在阅读此书,我注意到通过将Spring Security包含在您的构建文件中,默认情况下,整个应用程序都将启用授权。

答案 1 :(得分:-1)

您的代码没有错。您还需要设置默认配置,这将允许其他所有内容。 XML等效安全表达式可能是这样的(确保按正确的顺序排列):

 <security:http use-expressions="true" pattern="/**">
    <security:intercept-url pattern="/**" access="permitAll()"/>
 </security:http>

答案 2 :(得分:-1)

您可以允许访问您的某些目录:

http.authorizeRequests().antMatchers("/css/**", "/js/**", "/images/**").permitAll();