springCloud 学习第二篇——构建服务,并注册到eureka注册中心

复制上一篇创建好的项目,重新构建spring-boot项目:md-service-find;替换pom.xml文件;

项目结构:

一: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>md-service-find</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>md-service-find</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.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.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.30</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.RC1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

二:MdServiceFindApplication以及application.yml

package com.example.mdservicefind;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableEurekaClient
@ComponentScan
@RestController
public class MdServiceFindApplication {

    public static void main(String[] args) {
        SpringApplication.run(MdServiceFindApplication.class, args);
    }
    @GetMapping("/service")
    public String service(){
        return "service-f";
    }
}
server:
  port: 8760
spring:
  application:
    name: md-service-find
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/md_vue?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&allowMultiQueries=true
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20
mybatis:
  mapper-locations: classpath:mapping/*.xml
  type-aliases-package: com.example.mdservicefind

eureka:
  client:
     serviceUrl:
       defaultZone: http://localhost:8861/eureka/

三:几个类:DataMapper、DbUser、HelloController、MvcConfig、UserDetailInfo、WebSecurityConfig

package com.example.mdservicefind;

public interface DataMapper {
    DbUser getUserLoginInfo(String username);
}
package com.example.mdservicefind;

import lombok.Data;
import lombok.Getter;

@Data
public class DbUser {
    private String username;
    private String password;
    private Integer access_level;
    private String description;
}
package com.example.mdservicefind;

import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    @RequestMapping("/")
    public String index() {
        return "home";
    }
    @RequestMapping("/home")
    public String home() {
        return "home";
    }

    /*当我们访问这个URL的时候,Spring Security会帮我们验证当前用户是否有权限访问该地址。
     *官方推荐的鉴权注解方式,控制权限到请求方法级别。可通过三种方式的注解:
     *注解方式1:@Secured, spring自带的注解方法:securedEnabled = true
     *注解方式2:@PreAuthorize,方法调用前注解:securedEnabled = true
     *注解方式2:@RolesAllowed,非spring框架: jsr250Enabled = true
     *注意1:角色要填全名!
     *注意2:一定要在自定义的WebSecurityConfigurerAdapter中添加注解。@EnableGlobalMethodSecurity(axx=bxx)!axx/bxx见上
     */
    @Secured({"ROLE_ADMIN","ROLE_USER"})
    @RequestMapping("/hello")
    //@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
    public String hello(){
        return "hello";
    }

    @RequestMapping(value = "/login")
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/logout")
    public String logout() {
        return "home";
    }

    @RequestMapping(value = "/denied")
    public String denied() {
        return "denied";
    }

    @Secured("ROLE_ADMIN")
    @RequestMapping(value = "/admin")
    //@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public String admin() {
        return "admin";
    }
}
package com.example.mdservicefind;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Component
public class MvcConfig extends WebMvcConfigurerAdapter {

    //直接页面跳转,不经过Controller,这样在没有任何处理业务的时候,快捷的页面转向定义会节省好多代码
    @Override
    public void addViewControllers(ViewControllerRegistry registry)
    {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        //registry.addViewController("/hello").setViewName("hello");
        //registry.addViewController("/login").setViewName("login");
        //registry.addViewController("/denied").setViewName("denied");
        //registry.addViewController("/admin").setViewName("admin");
    }
}
package com.example.mdservicefind;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;

@Service
public class UserDetailInfo implements UserDetailsService {

    //数据库操作
    @Resource
    private DataMapper dbDataMapper;

    //必须重写,自己来实现登陆验证
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println("user["+username+"] is logining...");

        DbUser dbUser = dbDataMapper.getUserLoginInfo(username);
        if(dbUser==null)
        {
            System.out.println("user["+username+"] is not exist!");
            throw new UsernameNotFoundException(username + " do not exist!");
        }
        System.out.println("Get user info from db: "+ dbUser.toString());

        UserDetails user = new User(dbUser.getUsername(), dbUser.getPassword(), true, true, true, true,
                getAuthorities(dbUser.getAccess_level()));

        return user;
    }

    /**
     * 获得访问角色权限
     */
    public Collection<GrantedAuthority> getAuthorities(Integer access) {

        Collection<GrantedAuthority> authorities = new ArrayList<>();

        //所有的用户默认拥有ROLE_USER权限
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        if (access.compareTo(0) == 0) {
            // 如果参数access为0.则拥有ROLE_ADMIN权限
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }
        return authorities;
    }

}
package com.example.mdservicefind;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)  //控制权限到请求方法级别
//@EnableGlobalMethodSecurity(prePostEnabled = true)//方法调用前鉴权
@EnableWebSecurity //禁用Boot的默认Security配置,配合@Configuration启用自定义配置(需要扩展WebSecurityConfigurerAdapter)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //自定义认证对象
    @Autowired
    private UserDetailInfo urlUserService;

    //HTTP请求安全处理
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //请求权限配置
        http.authorizeRequests()
                //指定了/和/home不需要任何认证就可以访问,
                .antMatchers("/", "/home").permitAll()
                //任何请求,登录后方可访问。
                .anyRequest().authenticated()
                //登陆界面参数
                .and().formLogin().defaultSuccessUrl("/hello")/*.loginPage("/login").usernameParameter("username").passwordParameter("password")*/.permitAll()
                //设置注销成功后跳转页面,默认是跳转到登录页面
                .and().logout().logoutSuccessUrl("/home").permitAll()
                //权限访问失败界面,关键,如果不定义的话会抛出异常
                .and().exceptionHandling().accessDeniedPage("/denied")
        ;
        http.csrf().disable();
    }

    /*
     * 身份验证管理生成器。一定要重载!!!不然自定义的登陆校验不生效
     * */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(urlUserService)
		/*.passwordEncoder(new PasswordEncoder() {
			//可以自己定义密码匹配规则
			@Override
			public String encode(CharSequence rawPassword) {
				return (String)rawPassword;//MD5Util.encode((String) rawPassword);
			}
			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				System.out.println(encodedPassword + "---" + (String)rawPassword);
				return encodedPassword.equals((String) rawPassword);
			}
		})*/;
    }
}

四:mybatis/dbMapping.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.mdservicefind" >

    <resultMap id="UserLoginInfo" type="com.example.mdservicefind.DbUser">
        <id     column="username" property="username" jdbcType="VARCHAR"/>
        <result  column="password" property="password" jdbcType="VARCHAR"/>
        <result  column="access_level" property="access_level" jdbcType="FLOAT"/>
        <result  column="description" property="description" jdbcType="VARCHAR"/>
    </resultMap>

    <select id="getUserLoginInfo" resultMap ="UserLoginInfo" >
		select username, password, access_level,description from md_user t
		where 1=1 and t.username= #{username,jdbcType=VARCHAR}
	</select>
</mapper>

五:几个html:admin.html、denied.html、hello.html、home.html、login.html

1:admin.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Admin Page</title>
</head>
<body>
<h1>Admin Page!</h1>
<p>This is logged page. every ROLE_ADMIN can be visited.</p>
<p>
    Click <a th:href="@{/hello}">here</a> to hello page
</p>
<p>
    Click <a th:href="@{/logout}">here</a> to logout.
</p>
</body>
</html>

2:denied.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Denied visit page!</title>
</head>
<body>
<h1>Your access is denied</h1>
<p>This is a visit denied page.</p>
<p>
    Click <a th:href="@{/hello}">here</a> to hello page
</p>
<p>
    Click <a th:href="@{/logout}">here</a> to logout.
</p>
</body>
</html>

3:hello.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
<p>This is logged page. every body can be visited.</p>
<div sec:authorize="hasRole('ROLE_ADMIN')">
    <p>This is massage only ROLE_ADMIN can be visited.</p>
</div>
<!-- 通过标签鉴权,对应不同角色显示不同信息 -->
<div sec:authorize="hasRole('ROLE_USER')">
    <p>This is massage only ROLE_USER can be visited.</p>
</div>
<p>
    Click <a th:href="@{/logout}">here</a> to logout.
</p>
<p>
    Click <a th:href="@{/admin}">here</a> to admin page.
</p>
</body>
</html>

4:home.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example</title>
</head>
<body>
<h1>Welcome the home page!</h1>

<p>
    Click <a th:href="@{/hello}">here</a> to login.
</p>
</body>
</html>

5:login.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example</title>
</head>
<body>
<div th:if="${param.error}">Invalid username and password.</div>
<div th:if="${param.logout}">You have been logged out.</div>
<h2>使用账号密码登录</h2>
<form th:action="@{/login}" method="post">
    <div>
        <label> User Name : <input type="text" name="username" />
        </label>
    </div>
    <div>
        <label> Password: <input type="password" name="password" />
        </label>
    </div>
    <div>
        <input type="submit" value="Sign In" />
    </div>
</form>
</body>
</html>

至此,该spring-boot项目完成,感谢提供学习帮助的其他朋友的博客,此项目是在他的博客项目的基础上修改的,虽然我也记不住那个博客的地址了,不过还是表达一下感谢! 0.0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值