【问题标题】:spring boot secure rest api with spring security带有spring security的spring boot安全休息api
【发布时间】:2017-07-07 01:07:04
【问题描述】:

我有网络应用程序,我想保护我的其余 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 一些帮助

【问题讨论】:

    标签: java spring spring-boot spring-security


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我需要在不提示登录的情况下允许访问我的 html 文件
      • 您可以将 /html/** 添加到列表中,以访问该目录下的所有文件。它们是路径,在我的情况下,我将文件放在不同的目录中。如果您的文件位于根目录下,您只需添加“/**”即可。
      【解决方案3】:

      您的代码没有问题。您还需要设置默认配置,以允许其他所有操作。 XML等效的安全表达式可能是这样的(确保你把它放在正确的顺序):

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

      【讨论】:

      • 在 .antMatchers(HttpMethod.GET, "/api/**").authenticated() .antMatchers(HttpMethod.GET, "/**").permitAll() 之后尝试这些代码行
      猜你喜欢
      • 2017-08-19
      • 2016-04-19
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多